1 /* Python interface to values.
3 Copyright (C) 2008-2018 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
24 #include "target-float.h"
27 #include "expression.h"
31 #include "python-internal.h"
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 builtin_type (python_gdbarch)->builtin_long
41 /* Python's float type corresponds to C's double type. */
42 #define builtin_type_pyfloat builtin_type (python_gdbarch)->builtin_double
44 /* Python's long type corresponds to C's long long type. */
45 #define builtin_type_pylong builtin_type (python_gdbarch)->builtin_long_long
47 /* Python's long type corresponds to C's long long type. Unsigned version. */
48 #define builtin_type_upylong builtin_type \
49 (python_gdbarch)->builtin_unsigned_long_long
51 #define builtin_type_pybool \
52 language_bool_type (python_language, python_gdbarch)
54 #define builtin_type_pychar \
55 language_string_char_type (python_language, python_gdbarch)
57 typedef struct value_object
{
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 /* Called by the Python interpreter when deallocating a value object. */
76 valpy_dealloc (PyObject
*obj
)
78 value_object
*self
= (value_object
*) obj
;
80 /* Remove SELF from the global list. */
82 self
->prev
->next
= self
->next
;
85 gdb_assert (values_in_python
== self
);
86 values_in_python
= self
->next
;
89 self
->next
->prev
= self
->prev
;
91 value_free (self
->value
);
94 /* Use braces to appease gcc warning. *sigh* */
96 Py_DECREF (self
->address
);
101 Py_DECREF (self
->type
);
104 Py_XDECREF (self
->dynamic_type
);
106 Py_TYPE (self
)->tp_free (self
);
109 /* Helper to push a Value object on the global list. */
111 note_value (value_object
*value_obj
)
113 value_obj
->next
= values_in_python
;
115 value_obj
->next
->prev
= value_obj
;
116 value_obj
->prev
= NULL
;
117 values_in_python
= value_obj
;
120 /* Called when a new gdb.Value object needs to be allocated. Returns NULL on
121 error, with a python exception set. */
123 valpy_new (PyTypeObject
*subtype
, PyObject
*args
, PyObject
*keywords
)
125 struct value
*value
= NULL
; /* Initialize to appease gcc warning. */
126 value_object
*value_obj
;
128 if (PyTuple_Size (args
) != 1)
130 PyErr_SetString (PyExc_TypeError
, _("Value object creation takes only "
135 value_obj
= (value_object
*) subtype
->tp_alloc (subtype
, 1);
136 if (value_obj
== NULL
)
138 PyErr_SetString (PyExc_MemoryError
, _("Could not allocate memory to "
139 "create Value object."));
143 value
= convert_value_from_python (PyTuple_GetItem (args
, 0));
146 subtype
->tp_free (value_obj
);
150 value_obj
->value
= value
;
151 release_value_or_incref (value
);
152 value_obj
->address
= NULL
;
153 value_obj
->type
= NULL
;
154 value_obj
->dynamic_type
= NULL
;
155 note_value (value_obj
);
157 return (PyObject
*) value_obj
;
160 /* Iterate over all the Value objects, calling preserve_one_value on
163 gdbpy_preserve_values (const struct extension_language_defn
*extlang
,
164 struct objfile
*objfile
, htab_t copied_types
)
168 for (iter
= values_in_python
; iter
; iter
= iter
->next
)
169 preserve_one_value (iter
->value
, objfile
, copied_types
);
172 /* Given a value of a pointer type, apply the C unary * operator to it. */
174 valpy_dereference (PyObject
*self
, PyObject
*args
)
176 PyObject
*result
= NULL
;
180 struct value
*res_val
;
181 scoped_value_mark free_values
;
183 res_val
= value_ind (((value_object
*) self
)->value
);
184 result
= value_to_value_object (res_val
);
186 CATCH (except
, RETURN_MASK_ALL
)
188 GDB_PY_HANDLE_EXCEPTION (except
);
195 /* Given a value of a pointer type or a reference type, return the value
196 referenced. The difference between this function and valpy_dereference is
197 that the latter applies * unary operator to a value, which need not always
198 result in the value referenced. For example, for a value which is a reference
199 to an 'int' pointer ('int *'), valpy_dereference will result in a value of
200 type 'int' while valpy_referenced_value will result in a value of type
204 valpy_referenced_value (PyObject
*self
, PyObject
*args
)
206 PyObject
*result
= NULL
;
210 struct value
*self_val
, *res_val
;
211 scoped_value_mark free_values
;
213 self_val
= ((value_object
*) self
)->value
;
214 switch (TYPE_CODE (check_typedef (value_type (self_val
))))
217 res_val
= value_ind (self_val
);
220 case TYPE_CODE_RVALUE_REF
:
221 res_val
= coerce_ref (self_val
);
224 error(_("Trying to get the referenced value from a value which is "
225 "neither a pointer nor a reference."));
228 result
= value_to_value_object (res_val
);
230 CATCH (except
, RETURN_MASK_ALL
)
232 GDB_PY_HANDLE_EXCEPTION (except
);
239 /* Return a value which is a reference to the value. */
242 valpy_reference_value (PyObject
*self
, PyObject
*args
, enum type_code refcode
)
244 PyObject
*result
= NULL
;
248 struct value
*self_val
;
249 scoped_value_mark free_values
;
251 self_val
= ((value_object
*) self
)->value
;
252 result
= value_to_value_object (value_ref (self_val
, refcode
));
254 CATCH (except
, RETURN_MASK_ALL
)
256 GDB_PY_HANDLE_EXCEPTION (except
);
264 valpy_lvalue_reference_value (PyObject
*self
, PyObject
*args
)
266 return valpy_reference_value (self
, args
, TYPE_CODE_REF
);
270 valpy_rvalue_reference_value (PyObject
*self
, PyObject
*args
)
272 return valpy_reference_value (self
, args
, TYPE_CODE_RVALUE_REF
);
275 /* Return a "const" qualified version of the value. */
278 valpy_const_value (PyObject
*self
, PyObject
*args
)
280 PyObject
*result
= NULL
;
284 struct value
*self_val
, *res_val
;
285 scoped_value_mark free_values
;
287 self_val
= ((value_object
*) self
)->value
;
288 res_val
= make_cv_value (1, 0, self_val
);
289 result
= value_to_value_object (res_val
);
291 CATCH (except
, RETURN_MASK_ALL
)
293 GDB_PY_HANDLE_EXCEPTION (except
);
300 /* Return "&value". */
302 valpy_get_address (PyObject
*self
, void *closure
)
304 value_object
*val_obj
= (value_object
*) self
;
306 if (!val_obj
->address
)
310 struct value
*res_val
;
311 scoped_value_mark free_values
;
313 res_val
= value_addr (val_obj
->value
);
314 val_obj
->address
= value_to_value_object (res_val
);
316 CATCH (except
, RETURN_MASK_ALL
)
318 val_obj
->address
= Py_None
;
324 Py_XINCREF (val_obj
->address
);
326 return val_obj
->address
;
329 /* Return type of the value. */
331 valpy_get_type (PyObject
*self
, void *closure
)
333 value_object
*obj
= (value_object
*) self
;
337 obj
->type
= type_to_type_object (value_type (obj
->value
));
341 Py_INCREF (obj
->type
);
345 /* Return dynamic type of the value. */
348 valpy_get_dynamic_type (PyObject
*self
, void *closure
)
350 value_object
*obj
= (value_object
*) self
;
351 struct type
*type
= NULL
;
353 if (obj
->dynamic_type
!= NULL
)
355 Py_INCREF (obj
->dynamic_type
);
356 return obj
->dynamic_type
;
361 struct value
*val
= obj
->value
;
362 scoped_value_mark free_values
;
364 type
= value_type (val
);
365 type
= check_typedef (type
);
367 if (((TYPE_CODE (type
) == TYPE_CODE_PTR
) || TYPE_IS_REFERENCE (type
))
368 && (TYPE_CODE (TYPE_TARGET_TYPE (type
)) == TYPE_CODE_STRUCT
))
370 struct value
*target
;
371 int was_pointer
= TYPE_CODE (type
) == TYPE_CODE_PTR
;
374 target
= value_ind (val
);
376 target
= coerce_ref (val
);
377 type
= value_rtti_type (target
, NULL
, NULL
, NULL
);
382 type
= lookup_pointer_type (type
);
384 type
= lookup_lvalue_reference_type (type
);
387 else if (TYPE_CODE (type
) == TYPE_CODE_STRUCT
)
388 type
= value_rtti_type (val
, NULL
, NULL
, NULL
);
391 /* Re-use object's static type. */
395 CATCH (except
, RETURN_MASK_ALL
)
397 GDB_PY_HANDLE_EXCEPTION (except
);
402 obj
->dynamic_type
= valpy_get_type (self
, NULL
);
404 obj
->dynamic_type
= type_to_type_object (type
);
406 Py_XINCREF (obj
->dynamic_type
);
407 return obj
->dynamic_type
;
410 /* Implementation of gdb.Value.lazy_string ([encoding] [, length]) ->
411 string. Return a PyObject representing a lazy_string_object type.
412 A lazy string is a pointer to a string with an optional encoding and
413 length. If ENCODING is not given, encoding is set to None. If an
414 ENCODING is provided the encoding parameter is set to ENCODING, but
415 the string is not encoded.
416 If LENGTH is provided then the length parameter is set to LENGTH.
417 Otherwise if the value is an array of known length then the array's length
418 is used. Otherwise the length will be set to -1 (meaning first null of
421 Note: In order to not break any existing uses this allows creating
422 lazy strings from anything. PR 20769. E.g.,
423 gdb.parse_and_eval("my_int_variable").lazy_string().
424 "It's easier to relax restrictions than it is to impose them after the
425 fact." So we should be flagging any unintended uses as errors, but it's
426 perhaps too late for that. */
429 valpy_lazy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
431 gdb_py_longest length
= -1;
432 struct value
*value
= ((value_object
*) self
)->value
;
433 const char *user_encoding
= NULL
;
434 static const char *keywords
[] = { "encoding", "length", NULL
};
435 PyObject
*str_obj
= NULL
;
437 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|s" GDB_PY_LL_ARG
,
438 keywords
, &user_encoding
, &length
))
443 PyErr_SetString (PyExc_ValueError
, _("Invalid length."));
449 scoped_value_mark free_values
;
450 struct type
*type
, *realtype
;
453 type
= value_type (value
);
454 realtype
= check_typedef (type
);
456 switch (TYPE_CODE (realtype
))
458 case TYPE_CODE_ARRAY
:
460 LONGEST array_length
= -1;
461 LONGEST low_bound
, high_bound
;
463 /* PR 20786: There's no way to specify an array of length zero.
464 Record a length of [0,-1] which is how Ada does it. Anything
465 we do is broken, but this one possible solution. */
466 if (get_array_bounds (realtype
, &low_bound
, &high_bound
))
467 array_length
= high_bound
- low_bound
+ 1;
469 length
= array_length
;
470 else if (array_length
== -1)
472 type
= lookup_array_range_type (TYPE_TARGET_TYPE (realtype
),
475 else if (length
!= array_length
)
477 /* We need to create a new array type with the
479 if (length
> array_length
)
480 error (_("Length is larger than array size."));
481 type
= lookup_array_range_type (TYPE_TARGET_TYPE (realtype
),
483 low_bound
+ length
- 1);
485 addr
= value_address (value
);
489 /* If a length is specified we defer creating an array of the
490 specified width until we need to. */
491 addr
= value_as_address (value
);
494 /* Should flag an error here. PR 20769. */
495 addr
= value_address (value
);
499 str_obj
= gdbpy_create_lazy_string_object (addr
, length
, user_encoding
,
502 CATCH (except
, RETURN_MASK_ALL
)
504 GDB_PY_HANDLE_EXCEPTION (except
);
511 /* Implementation of gdb.Value.string ([encoding] [, errors]
512 [, length]) -> string. Return Unicode string with value contents.
513 If ENCODING is not given, the string is assumed to be encoded in
514 the target's charset. If LENGTH is provided, only fetch string to
515 the length provided. */
518 valpy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
522 struct value
*value
= ((value_object
*) self
)->value
;
524 const char *encoding
= NULL
;
525 const char *errors
= NULL
;
526 const char *user_encoding
= NULL
;
527 const char *la_encoding
= NULL
;
528 struct type
*char_type
;
529 static const char *keywords
[] = { "encoding", "errors", "length", NULL
};
531 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "|ssi", keywords
,
532 &user_encoding
, &errors
, &length
))
537 LA_GET_STRING (value
, &buffer
, &length
, &char_type
, &la_encoding
);
539 CATCH (except
, RETURN_MASK_ALL
)
541 GDB_PY_HANDLE_EXCEPTION (except
);
545 encoding
= (user_encoding
&& *user_encoding
) ? user_encoding
: la_encoding
;
546 unicode
= PyUnicode_Decode ((const char *) buffer
,
547 length
* TYPE_LENGTH (char_type
),
554 /* A helper function that implements the various cast operators. */
557 valpy_do_cast (PyObject
*self
, PyObject
*args
, enum exp_opcode op
)
559 PyObject
*type_obj
, *result
= NULL
;
562 if (! PyArg_ParseTuple (args
, "O", &type_obj
))
565 type
= type_object_to_type (type_obj
);
568 PyErr_SetString (PyExc_RuntimeError
,
569 _("Argument must be a type."));
575 struct value
*val
= ((value_object
*) self
)->value
;
576 struct value
*res_val
;
577 scoped_value_mark free_values
;
579 if (op
== UNOP_DYNAMIC_CAST
)
580 res_val
= value_dynamic_cast (type
, val
);
581 else if (op
== UNOP_REINTERPRET_CAST
)
582 res_val
= value_reinterpret_cast (type
, val
);
585 gdb_assert (op
== UNOP_CAST
);
586 res_val
= value_cast (type
, val
);
589 result
= value_to_value_object (res_val
);
591 CATCH (except
, RETURN_MASK_ALL
)
593 GDB_PY_HANDLE_EXCEPTION (except
);
600 /* Implementation of the "cast" method. */
603 valpy_cast (PyObject
*self
, PyObject
*args
)
605 return valpy_do_cast (self
, args
, UNOP_CAST
);
608 /* Implementation of the "dynamic_cast" method. */
611 valpy_dynamic_cast (PyObject
*self
, PyObject
*args
)
613 return valpy_do_cast (self
, args
, UNOP_DYNAMIC_CAST
);
616 /* Implementation of the "reinterpret_cast" method. */
619 valpy_reinterpret_cast (PyObject
*self
, PyObject
*args
)
621 return valpy_do_cast (self
, args
, UNOP_REINTERPRET_CAST
);
625 valpy_length (PyObject
*self
)
627 /* We don't support getting the number of elements in a struct / class. */
628 PyErr_SetString (PyExc_NotImplementedError
,
629 _("Invalid operation on gdb.Value."));
633 /* Return 1 if the gdb.Field object FIELD is present in the value V.
634 Returns 0 otherwise. If any Python error occurs, -1 is returned. */
637 value_has_field (struct value
*v
, PyObject
*field
)
639 struct type
*parent_type
, *val_type
;
640 enum type_code type_code
;
641 gdbpy_ref
<> type_object (PyObject_GetAttrString (field
, "parent_type"));
644 if (type_object
== NULL
)
647 parent_type
= type_object_to_type (type_object
.get ());
648 if (parent_type
== NULL
)
650 PyErr_SetString (PyExc_TypeError
,
651 _("'parent_type' attribute of gdb.Field object is not a"
652 "gdb.Type object."));
658 val_type
= value_type (v
);
659 val_type
= check_typedef (val_type
);
660 if (TYPE_IS_REFERENCE (val_type
) || TYPE_CODE (val_type
) == TYPE_CODE_PTR
)
661 val_type
= check_typedef (TYPE_TARGET_TYPE (val_type
));
663 type_code
= TYPE_CODE (val_type
);
664 if ((type_code
== TYPE_CODE_STRUCT
|| type_code
== TYPE_CODE_UNION
)
665 && types_equal (val_type
, parent_type
))
670 CATCH (except
, RETURN_MASK_ALL
)
672 GDB_PY_SET_HANDLE_EXCEPTION (except
);
679 /* Return the value of a flag FLAG_NAME in a gdb.Field object FIELD.
680 Returns 1 if the flag value is true, 0 if it is false, and -1 if
681 a Python error occurs. */
684 get_field_flag (PyObject
*field
, const char *flag_name
)
686 gdbpy_ref
<> flag_object (PyObject_GetAttrString (field
, flag_name
));
688 if (flag_object
== NULL
)
691 return PyObject_IsTrue (flag_object
.get ());
694 /* Return the "type" attribute of a gdb.Field object.
695 Returns NULL on error, with a Python exception set. */
698 get_field_type (PyObject
*field
)
700 gdbpy_ref
<> ftype_obj (PyObject_GetAttrString (field
, "type"));
703 if (ftype_obj
== NULL
)
705 ftype
= type_object_to_type (ftype_obj
.get ());
707 PyErr_SetString (PyExc_TypeError
,
708 _("'type' attribute of gdb.Field object is not a "
709 "gdb.Type object."));
714 /* Given string name or a gdb.Field object corresponding to an element inside
715 a structure, return its value object. Returns NULL on error, with a python
719 valpy_getitem (PyObject
*self
, PyObject
*key
)
721 struct gdb_exception except
= exception_none
;
722 value_object
*self_value
= (value_object
*) self
;
723 gdb::unique_xmalloc_ptr
<char> field
;
724 struct type
*base_class_type
= NULL
, *field_type
= NULL
;
726 PyObject
*result
= NULL
;
728 if (gdbpy_is_string (key
))
730 field
= python_string_to_host_string (key
);
734 else if (gdbpy_is_field (key
))
736 int is_base_class
, valid_field
;
738 valid_field
= value_has_field (self_value
->value
, key
);
741 else if (valid_field
== 0)
743 PyErr_SetString (PyExc_TypeError
,
744 _("Invalid lookup for a field not contained in "
750 is_base_class
= get_field_flag (key
, "is_base_class");
751 if (is_base_class
< 0)
753 else if (is_base_class
> 0)
755 base_class_type
= get_field_type (key
);
756 if (base_class_type
== NULL
)
761 gdbpy_ref
<> name_obj (PyObject_GetAttrString (key
, "name"));
763 if (name_obj
== NULL
)
766 if (name_obj
!= Py_None
)
768 field
= python_string_to_host_string (name_obj
.get ());
774 if (!PyObject_HasAttrString (key
, "bitpos"))
776 PyErr_SetString (PyExc_AttributeError
,
777 _("gdb.Field object has no name and no "
778 "'bitpos' attribute."));
782 gdbpy_ref
<> bitpos_obj (PyObject_GetAttrString (key
, "bitpos"));
783 if (bitpos_obj
== NULL
)
785 if (!gdb_py_int_as_long (bitpos_obj
.get (), &bitpos
))
788 field_type
= get_field_type (key
);
789 if (field_type
== NULL
)
797 struct value
*tmp
= self_value
->value
;
798 struct value
*res_val
= NULL
;
799 scoped_value_mark free_values
;
802 res_val
= value_struct_elt (&tmp
, NULL
, field
.get (), NULL
,
803 "struct/class/union");
804 else if (bitpos
>= 0)
805 res_val
= value_struct_elt_bitpos (&tmp
, bitpos
, field_type
,
806 "struct/class/union");
807 else if (base_class_type
!= NULL
)
809 struct type
*val_type
;
811 val_type
= check_typedef (value_type (tmp
));
812 if (TYPE_CODE (val_type
) == TYPE_CODE_PTR
)
813 res_val
= value_cast (lookup_pointer_type (base_class_type
), tmp
);
814 else if (TYPE_CODE (val_type
) == TYPE_CODE_REF
)
815 res_val
= value_cast (lookup_lvalue_reference_type (base_class_type
),
817 else if (TYPE_CODE (val_type
) == TYPE_CODE_RVALUE_REF
)
818 res_val
= value_cast (lookup_rvalue_reference_type (base_class_type
),
821 res_val
= value_cast (base_class_type
, tmp
);
825 /* Assume we are attempting an array access, and let the
826 value code throw an exception if the index has an invalid
828 struct value
*idx
= convert_value_from_python (key
);
832 /* Check the value's type is something that can be accessed via
836 tmp
= coerce_ref (tmp
);
837 type
= check_typedef (value_type (tmp
));
838 if (TYPE_CODE (type
) != TYPE_CODE_ARRAY
839 && TYPE_CODE (type
) != TYPE_CODE_PTR
)
840 error (_("Cannot subscript requested type."));
842 res_val
= value_subscript (tmp
, value_as_long (idx
));
847 result
= value_to_value_object (res_val
);
849 CATCH (ex
, RETURN_MASK_ALL
)
855 GDB_PY_HANDLE_EXCEPTION (except
);
861 valpy_setitem (PyObject
*self
, PyObject
*key
, PyObject
*value
)
863 PyErr_Format (PyExc_NotImplementedError
,
864 _("Setting of struct elements is not currently supported."));
868 /* Called by the Python interpreter to perform an inferior function
869 call on the value. Returns NULL on error, with a python exception set. */
871 valpy_call (PyObject
*self
, PyObject
*args
, PyObject
*keywords
)
873 Py_ssize_t args_count
;
874 struct value
*function
= ((value_object
*) self
)->value
;
875 struct value
**vargs
= NULL
;
876 struct type
*ftype
= NULL
;
877 PyObject
*result
= NULL
;
881 ftype
= check_typedef (value_type (function
));
883 CATCH (except
, RETURN_MASK_ALL
)
885 GDB_PY_HANDLE_EXCEPTION (except
);
889 if (TYPE_CODE (ftype
) != TYPE_CODE_FUNC
)
891 PyErr_SetString (PyExc_RuntimeError
,
892 _("Value is not callable (not TYPE_CODE_FUNC)."));
896 if (! PyTuple_Check (args
))
898 PyErr_SetString (PyExc_TypeError
,
899 _("Inferior arguments must be provided in a tuple."));
903 args_count
= PyTuple_Size (args
);
908 vargs
= XALLOCAVEC (struct value
*, args_count
);
909 for (i
= 0; i
< args_count
; i
++)
911 PyObject
*item
= PyTuple_GetItem (args
, i
);
916 vargs
[i
] = convert_value_from_python (item
);
917 if (vargs
[i
] == NULL
)
924 scoped_value_mark free_values
;
925 struct value
*return_value
;
927 return_value
= call_function_by_hand (function
, NULL
,
929 result
= value_to_value_object (return_value
);
931 CATCH (except
, RETURN_MASK_ALL
)
933 GDB_PY_HANDLE_EXCEPTION (except
);
940 /* Called by the Python interpreter to obtain string representation
943 valpy_str (PyObject
*self
)
945 struct value_print_options opts
;
947 get_user_print_options (&opts
);
954 common_val_print (((value_object
*) self
)->value
, &stb
, 0,
955 &opts
, python_language
);
957 CATCH (except
, RETURN_MASK_ALL
)
959 GDB_PY_HANDLE_EXCEPTION (except
);
963 return PyUnicode_Decode (stb
.c_str (), stb
.size (), host_charset (), NULL
);
966 /* Implements gdb.Value.is_optimized_out. */
968 valpy_get_is_optimized_out (PyObject
*self
, void *closure
)
970 struct value
*value
= ((value_object
*) self
)->value
;
975 opt
= value_optimized_out (value
);
977 CATCH (except
, RETURN_MASK_ALL
)
979 GDB_PY_HANDLE_EXCEPTION (except
);
989 /* Implements gdb.Value.is_lazy. */
991 valpy_get_is_lazy (PyObject
*self
, void *closure
)
993 struct value
*value
= ((value_object
*) self
)->value
;
998 opt
= value_lazy (value
);
1000 CATCH (except
, RETURN_MASK_ALL
)
1002 GDB_PY_HANDLE_EXCEPTION (except
);
1012 /* Implements gdb.Value.fetch_lazy (). */
1014 valpy_fetch_lazy (PyObject
*self
, PyObject
*args
)
1016 struct value
*value
= ((value_object
*) self
)->value
;
1020 if (value_lazy (value
))
1021 value_fetch_lazy (value
);
1023 CATCH (except
, RETURN_MASK_ALL
)
1025 GDB_PY_HANDLE_EXCEPTION (except
);
1032 /* Calculate and return the address of the PyObject as the value of
1033 the builtin __hash__ call. */
1035 valpy_hash (PyObject
*self
)
1037 return (intptr_t) self
;
1055 /* If TYPE is a reference, return the target; otherwise return TYPE. */
1056 #define STRIP_REFERENCE(TYPE) \
1057 (TYPE_IS_REFERENCE (TYPE) ? (TYPE_TARGET_TYPE (TYPE)) : (TYPE))
1059 /* Helper for valpy_binop. Returns a value object which is the result
1060 of applying the operation specified by OPCODE to the given
1061 arguments. Throws a GDB exception on error. */
1064 valpy_binop_throw (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
1066 PyObject
*result
= NULL
;
1068 struct value
*arg1
, *arg2
;
1069 struct value
*res_val
= NULL
;
1070 enum exp_opcode op
= OP_NULL
;
1073 scoped_value_mark free_values
;
1075 /* If the gdb.Value object is the second operand, then it will be
1076 passed to us as the OTHER argument, and SELF will be an entirely
1077 different kind of object, altogether. Because of this, we can't
1078 assume self is a gdb.Value object and need to convert it from
1080 arg1
= convert_value_from_python (self
);
1084 arg2
= convert_value_from_python (other
);
1092 struct type
*ltype
= value_type (arg1
);
1093 struct type
*rtype
= value_type (arg2
);
1095 ltype
= check_typedef (ltype
);
1096 ltype
= STRIP_REFERENCE (ltype
);
1097 rtype
= check_typedef (rtype
);
1098 rtype
= STRIP_REFERENCE (rtype
);
1101 if (TYPE_CODE (ltype
) == TYPE_CODE_PTR
1102 && is_integral_type (rtype
))
1103 res_val
= value_ptradd (arg1
, value_as_long (arg2
));
1104 else if (TYPE_CODE (rtype
) == TYPE_CODE_PTR
1105 && is_integral_type (ltype
))
1106 res_val
= value_ptradd (arg2
, value_as_long (arg1
));
1116 struct type
*ltype
= value_type (arg1
);
1117 struct type
*rtype
= value_type (arg2
);
1119 ltype
= check_typedef (ltype
);
1120 ltype
= STRIP_REFERENCE (ltype
);
1121 rtype
= check_typedef (rtype
);
1122 rtype
= STRIP_REFERENCE (rtype
);
1125 if (TYPE_CODE (ltype
) == TYPE_CODE_PTR
1126 && TYPE_CODE (rtype
) == TYPE_CODE_PTR
)
1127 /* A ptrdiff_t for the target would be preferable here. */
1128 res_val
= value_from_longest (builtin_type_pyint
,
1129 value_ptrdiff (arg1
, arg2
));
1130 else if (TYPE_CODE (ltype
) == TYPE_CODE_PTR
1131 && is_integral_type (rtype
))
1132 res_val
= value_ptradd (arg1
, - value_as_long (arg2
));
1159 op
= BINOP_BITWISE_AND
;
1162 op
= BINOP_BITWISE_IOR
;
1165 op
= BINOP_BITWISE_XOR
;
1171 if (binop_user_defined_p (op
, arg1
, arg2
))
1172 res_val
= value_x_binop (arg1
, arg2
, op
, OP_NULL
, EVAL_NORMAL
);
1174 res_val
= value_binop (arg1
, arg2
, op
);
1178 result
= value_to_value_object (res_val
);
1183 /* Returns a value object which is the result of applying the operation
1184 specified by OPCODE to the given arguments. Returns NULL on error, with
1185 a python exception set. */
1187 valpy_binop (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
1189 PyObject
*result
= NULL
;
1193 result
= valpy_binop_throw (opcode
, self
, other
);
1195 CATCH (except
, RETURN_MASK_ALL
)
1197 GDB_PY_HANDLE_EXCEPTION (except
);
1205 valpy_add (PyObject
*self
, PyObject
*other
)
1207 return valpy_binop (VALPY_ADD
, self
, other
);
1211 valpy_subtract (PyObject
*self
, PyObject
*other
)
1213 return valpy_binop (VALPY_SUB
, self
, other
);
1217 valpy_multiply (PyObject
*self
, PyObject
*other
)
1219 return valpy_binop (VALPY_MUL
, self
, other
);
1223 valpy_divide (PyObject
*self
, PyObject
*other
)
1225 return valpy_binop (VALPY_DIV
, self
, other
);
1229 valpy_remainder (PyObject
*self
, PyObject
*other
)
1231 return valpy_binop (VALPY_REM
, self
, other
);
1235 valpy_power (PyObject
*self
, PyObject
*other
, PyObject
*unused
)
1237 /* We don't support the ternary form of pow. I don't know how to express
1238 that, so let's just throw NotImplementedError to at least do something
1240 if (unused
!= Py_None
)
1242 PyErr_SetString (PyExc_NotImplementedError
,
1243 "Invalid operation on gdb.Value.");
1247 return valpy_binop (VALPY_POW
, self
, other
);
1251 valpy_negative (PyObject
*self
)
1253 PyObject
*result
= NULL
;
1257 /* Perhaps overkill, but consistency has some virtue. */
1258 scoped_value_mark free_values
;
1261 val
= value_neg (((value_object
*) self
)->value
);
1262 result
= value_to_value_object (val
);
1264 CATCH (except
, RETURN_MASK_ALL
)
1266 GDB_PY_HANDLE_EXCEPTION (except
);
1274 valpy_positive (PyObject
*self
)
1276 return value_to_value_object (((value_object
*) self
)->value
);
1280 valpy_absolute (PyObject
*self
)
1282 struct value
*value
= ((value_object
*) self
)->value
;
1287 scoped_value_mark free_values
;
1289 if (value_less (value
, value_zero (value_type (value
), not_lval
)))
1292 CATCH (except
, RETURN_MASK_ALL
)
1294 GDB_PY_HANDLE_EXCEPTION (except
);
1299 return valpy_positive (self
);
1301 return valpy_negative (self
);
1304 /* Implements boolean evaluation of gdb.Value. */
1306 valpy_nonzero (PyObject
*self
)
1308 struct gdb_exception except
= exception_none
;
1309 value_object
*self_value
= (value_object
*) self
;
1311 int nonzero
= 0; /* Appease GCC warning. */
1315 type
= check_typedef (value_type (self_value
->value
));
1317 if (is_integral_type (type
) || TYPE_CODE (type
) == TYPE_CODE_PTR
)
1318 nonzero
= !!value_as_long (self_value
->value
);
1319 else if (is_floating_value (self_value
->value
))
1320 nonzero
= !target_float_is_zero (value_contents (self_value
->value
),
1323 /* All other values are True. */
1326 CATCH (ex
, RETURN_MASK_ALL
)
1332 /* This is not documented in the Python documentation, but if this
1333 function fails, return -1 as slot_nb_nonzero does (the default
1334 Python nonzero function). */
1335 GDB_PY_SET_HANDLE_EXCEPTION (except
);
1340 /* Implements ~ for value objects. */
1342 valpy_invert (PyObject
*self
)
1344 struct value
*val
= NULL
;
1348 val
= value_complement (((value_object
*) self
)->value
);
1350 CATCH (except
, RETURN_MASK_ALL
)
1352 GDB_PY_HANDLE_EXCEPTION (except
);
1356 return value_to_value_object (val
);
1359 /* Implements left shift for value objects. */
1361 valpy_lsh (PyObject
*self
, PyObject
*other
)
1363 return valpy_binop (VALPY_LSH
, self
, other
);
1366 /* Implements right shift for value objects. */
1368 valpy_rsh (PyObject
*self
, PyObject
*other
)
1370 return valpy_binop (VALPY_RSH
, self
, other
);
1373 /* Implements bitwise and for value objects. */
1375 valpy_and (PyObject
*self
, PyObject
*other
)
1377 return valpy_binop (VALPY_BITAND
, self
, other
);
1380 /* Implements bitwise or for value objects. */
1382 valpy_or (PyObject
*self
, PyObject
*other
)
1384 return valpy_binop (VALPY_BITOR
, self
, other
);
1387 /* Implements bitwise xor for value objects. */
1389 valpy_xor (PyObject
*self
, PyObject
*other
)
1391 return valpy_binop (VALPY_BITXOR
, self
, other
);
1394 /* Helper for valpy_richcompare. Implements comparison operations for
1395 value objects. Returns true/false on success. Returns -1 with a
1396 Python exception set if a Python error is detected. Throws a GDB
1397 exception on other errors (memory error, etc.). */
1400 valpy_richcompare_throw (PyObject
*self
, PyObject
*other
, int op
)
1403 struct value
*value_other
;
1404 struct value
*value_self
;
1406 scoped_value_mark free_values
;
1408 value_other
= convert_value_from_python (other
);
1409 if (value_other
== NULL
)
1412 value_self
= ((value_object
*) self
)->value
;
1417 result
= value_less (value_self
, value_other
);
1420 result
= value_less (value_self
, value_other
)
1421 || value_equal (value_self
, value_other
);
1424 result
= value_equal (value_self
, value_other
);
1427 result
= !value_equal (value_self
, value_other
);
1430 result
= value_less (value_other
, value_self
);
1433 result
= (value_less (value_other
, value_self
)
1434 || value_equal (value_self
, value_other
));
1438 PyErr_SetString (PyExc_NotImplementedError
,
1439 _("Invalid operation on gdb.Value."));
1448 /* Implements comparison operations for value objects. Returns NULL on error,
1449 with a python exception set. */
1451 valpy_richcompare (PyObject
*self
, PyObject
*other
, int op
)
1455 if (other
== Py_None
)
1456 /* Comparing with None is special. From what I can tell, in Python
1457 None is smaller than anything else. */
1469 PyErr_SetString (PyExc_NotImplementedError
,
1470 _("Invalid operation on gdb.Value."));
1476 result
= valpy_richcompare_throw (self
, other
, op
);
1478 CATCH (except
, RETURN_MASK_ALL
)
1480 GDB_PY_HANDLE_EXCEPTION (except
);
1484 /* In this case, the Python exception has already been set. */
1495 /* Implements conversion to int. */
1497 valpy_int (PyObject
*self
)
1499 struct value
*value
= ((value_object
*) self
)->value
;
1500 struct type
*type
= value_type (value
);
1505 if (!is_integral_type (type
))
1506 error (_("Cannot convert value to int."));
1508 l
= value_as_long (value
);
1510 CATCH (except
, RETURN_MASK_ALL
)
1512 GDB_PY_HANDLE_EXCEPTION (except
);
1516 return gdb_py_object_from_longest (l
);
1520 /* Implements conversion to long. */
1522 valpy_long (PyObject
*self
)
1524 struct value
*value
= ((value_object
*) self
)->value
;
1525 struct type
*type
= value_type (value
);
1530 type
= check_typedef (type
);
1532 if (!is_integral_type (type
)
1533 && TYPE_CODE (type
) != TYPE_CODE_PTR
)
1534 error (_("Cannot convert value to long."));
1536 l
= value_as_long (value
);
1538 CATCH (except
, RETURN_MASK_ALL
)
1540 GDB_PY_HANDLE_EXCEPTION (except
);
1544 if (TYPE_UNSIGNED (type
))
1545 return gdb_py_long_from_ulongest (l
);
1547 return gdb_py_long_from_longest (l
);
1550 /* Implements conversion to float. */
1552 valpy_float (PyObject
*self
)
1554 struct value
*value
= ((value_object
*) self
)->value
;
1555 struct type
*type
= value_type (value
);
1560 type
= check_typedef (type
);
1562 if (TYPE_CODE (type
) != TYPE_CODE_FLT
|| !is_floating_value (value
))
1563 error (_("Cannot convert value to float."));
1565 d
= target_float_to_host_double (value_contents (value
), type
);
1567 CATCH (except
, RETURN_MASK_ALL
)
1569 GDB_PY_HANDLE_EXCEPTION (except
);
1573 return PyFloat_FromDouble (d
);
1576 /* Returns an object for a value which is released from the all_values chain,
1577 so its lifetime is not bound to the execution of a command. */
1579 value_to_value_object (struct value
*val
)
1581 value_object
*val_obj
;
1583 val_obj
= PyObject_New (value_object
, &value_object_type
);
1584 if (val_obj
!= NULL
)
1586 val_obj
->value
= val
;
1587 release_value_or_incref (val
);
1588 val_obj
->address
= NULL
;
1589 val_obj
->type
= NULL
;
1590 val_obj
->dynamic_type
= NULL
;
1591 note_value (val_obj
);
1594 return (PyObject
*) val_obj
;
1597 /* Returns a borrowed reference to the struct value corresponding to
1598 the given value object. */
1600 value_object_to_value (PyObject
*self
)
1604 if (! PyObject_TypeCheck (self
, &value_object_type
))
1606 real
= (value_object
*) self
;
1610 /* Try to convert a Python value to a gdb value. If the value cannot
1611 be converted, set a Python exception and return NULL. Returns a
1612 reference to a new value on the all_values chain. */
1615 convert_value_from_python (PyObject
*obj
)
1617 struct value
*value
= NULL
; /* -Wall */
1620 gdb_assert (obj
!= NULL
);
1624 if (PyBool_Check (obj
))
1626 cmp
= PyObject_IsTrue (obj
);
1628 value
= value_from_longest (builtin_type_pybool
, cmp
);
1630 /* Make a long logic check first. In Python 3.x, internally,
1631 all integers are represented as longs. In Python 2.x, there
1632 is still a differentiation internally between a PyInt and a
1633 PyLong. Explicitly do this long check conversion first. In
1634 GDB, for Python 3.x, we #ifdef PyInt = PyLong. This check has
1635 to be done first to ensure we do not lose information in the
1636 conversion process. */
1637 else if (PyLong_Check (obj
))
1639 LONGEST l
= PyLong_AsLongLong (obj
);
1641 if (PyErr_Occurred ())
1643 /* If the error was an overflow, we can try converting to
1644 ULONGEST instead. */
1645 if (PyErr_ExceptionMatches (PyExc_OverflowError
))
1647 PyObject
*etype
, *evalue
, *etraceback
;
1649 PyErr_Fetch (&etype
, &evalue
, &etraceback
);
1650 gdbpy_ref
<> zero (PyInt_FromLong (0));
1652 /* Check whether obj is positive. */
1653 if (PyObject_RichCompareBool (obj
, zero
.get (), Py_GT
) > 0)
1657 ul
= PyLong_AsUnsignedLongLong (obj
);
1658 if (! PyErr_Occurred ())
1659 value
= value_from_ulongest (builtin_type_upylong
, ul
);
1662 /* There's nothing we can do. */
1663 PyErr_Restore (etype
, evalue
, etraceback
);
1667 value
= value_from_longest (builtin_type_pylong
, l
);
1669 #if PY_MAJOR_VERSION == 2
1670 else if (PyInt_Check (obj
))
1672 long l
= PyInt_AsLong (obj
);
1674 if (! PyErr_Occurred ())
1675 value
= value_from_longest (builtin_type_pyint
, l
);
1678 else if (PyFloat_Check (obj
))
1680 double d
= PyFloat_AsDouble (obj
);
1682 if (! PyErr_Occurred ())
1684 value
= allocate_value (builtin_type_pyfloat
);
1685 target_float_from_host_double (value_contents_raw (value
),
1686 value_type (value
), d
);
1689 else if (gdbpy_is_string (obj
))
1691 gdb::unique_xmalloc_ptr
<char> s
1692 = python_string_to_target_string (obj
);
1694 value
= value_cstring (s
.get (), strlen (s
.get ()),
1695 builtin_type_pychar
);
1697 else if (PyObject_TypeCheck (obj
, &value_object_type
))
1698 value
= value_copy (((value_object
*) obj
)->value
);
1699 else if (gdbpy_is_lazy_string (obj
))
1703 result
= PyObject_CallMethodObjArgs (obj
, gdbpy_value_cst
, NULL
);
1704 value
= value_copy (((value_object
*) result
)->value
);
1708 PyErr_Format (PyExc_TypeError
,
1709 _("Could not convert Python object: %S."), obj
);
1711 PyErr_Format (PyExc_TypeError
,
1712 _("Could not convert Python object: %s."),
1713 PyString_AsString (PyObject_Str (obj
)));
1716 CATCH (except
, RETURN_MASK_ALL
)
1718 PyErr_Format (except
.reason
== RETURN_QUIT
1719 ? PyExc_KeyboardInterrupt
: PyExc_RuntimeError
,
1720 "%s", except
.message
);
1728 /* Returns value object in the ARGth position in GDB's history. */
1730 gdbpy_history (PyObject
*self
, PyObject
*args
)
1733 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
1735 if (!PyArg_ParseTuple (args
, "i", &i
))
1740 res_val
= access_value_history (i
);
1742 CATCH (except
, RETURN_MASK_ALL
)
1744 GDB_PY_HANDLE_EXCEPTION (except
);
1748 return value_to_value_object (res_val
);
1751 /* Returns 1 in OBJ is a gdb.Value object, 0 otherwise. */
1754 gdbpy_is_value_object (PyObject
*obj
)
1756 return PyObject_TypeCheck (obj
, &value_object_type
);
1760 gdbpy_initialize_values (void)
1762 if (PyType_Ready (&value_object_type
) < 0)
1765 return gdb_pymodule_addobject (gdb_module
, "Value",
1766 (PyObject
*) &value_object_type
);
1771 static gdb_PyGetSetDef value_object_getset
[] = {
1772 { "address", valpy_get_address
, NULL
, "The address of the value.",
1774 { "is_optimized_out", valpy_get_is_optimized_out
, NULL
,
1775 "Boolean telling whether the value is optimized "
1776 "out (i.e., not available).",
1778 { "type", valpy_get_type
, NULL
, "Type of the value.", NULL
},
1779 { "dynamic_type", valpy_get_dynamic_type
, NULL
,
1780 "Dynamic type of the value.", NULL
},
1781 { "is_lazy", valpy_get_is_lazy
, NULL
,
1782 "Boolean telling whether the value is lazy (not fetched yet\n\
1783 from the inferior). A lazy value is fetched when needed, or when\n\
1784 the \"fetch_lazy()\" method is called.", NULL
},
1785 {NULL
} /* Sentinel */
1788 static PyMethodDef value_object_methods
[] = {
1789 { "cast", valpy_cast
, METH_VARARGS
, "Cast the value to the supplied type." },
1790 { "dynamic_cast", valpy_dynamic_cast
, METH_VARARGS
,
1791 "dynamic_cast (gdb.Type) -> gdb.Value\n\
1792 Cast the value to the supplied type, as if by the C++ dynamic_cast operator."
1794 { "reinterpret_cast", valpy_reinterpret_cast
, METH_VARARGS
,
1795 "reinterpret_cast (gdb.Type) -> gdb.Value\n\
1796 Cast the value to the supplied type, as if by the C++\n\
1797 reinterpret_cast operator."
1799 { "dereference", valpy_dereference
, METH_NOARGS
, "Dereferences the value." },
1800 { "referenced_value", valpy_referenced_value
, METH_NOARGS
,
1801 "Return the value referenced by a TYPE_CODE_REF or TYPE_CODE_PTR value." },
1802 { "reference_value", valpy_lvalue_reference_value
, METH_NOARGS
,
1803 "Return a value of type TYPE_CODE_REF referencing this value." },
1804 { "rvalue_reference_value", valpy_rvalue_reference_value
, METH_NOARGS
,
1805 "Return a value of type TYPE_CODE_RVALUE_REF referencing this value." },
1806 { "const_value", valpy_const_value
, METH_NOARGS
,
1807 "Return a 'const' qualied version of the same value." },
1808 { "lazy_string", (PyCFunction
) valpy_lazy_string
,
1809 METH_VARARGS
| METH_KEYWORDS
,
1810 "lazy_string ([encoding] [, length]) -> lazy_string\n\
1811 Return a lazy string representation of the value." },
1812 { "string", (PyCFunction
) valpy_string
, METH_VARARGS
| METH_KEYWORDS
,
1813 "string ([encoding] [, errors] [, length]) -> string\n\
1814 Return Unicode string representation of the value." },
1815 { "fetch_lazy", valpy_fetch_lazy
, METH_NOARGS
,
1816 "Fetches the value from the inferior, if it was lazy." },
1817 {NULL
} /* Sentinel */
1820 static PyNumberMethods value_object_as_number
= {
1828 NULL
, /* nb_divmod */
1829 valpy_power
, /* nb_power */
1830 valpy_negative
, /* nb_negative */
1831 valpy_positive
, /* nb_positive */
1832 valpy_absolute
, /* nb_absolute */
1833 valpy_nonzero
, /* nb_nonzero */
1834 valpy_invert
, /* nb_invert */
1835 valpy_lsh
, /* nb_lshift */
1836 valpy_rsh
, /* nb_rshift */
1837 valpy_and
, /* nb_and */
1838 valpy_xor
, /* nb_xor */
1839 valpy_or
, /* nb_or */
1841 valpy_long
, /* nb_int */
1842 NULL
, /* reserved */
1844 NULL
, /* nb_coerce */
1845 valpy_int
, /* nb_int */
1846 valpy_long
, /* nb_long */
1848 valpy_float
, /* nb_float */
1853 NULL
, /* nb_inplace_add */
1854 NULL
, /* nb_inplace_subtract */
1855 NULL
, /* nb_inplace_multiply */
1857 NULL
, /* nb_inplace_divide */
1859 NULL
, /* nb_inplace_remainder */
1860 NULL
, /* nb_inplace_power */
1861 NULL
, /* nb_inplace_lshift */
1862 NULL
, /* nb_inplace_rshift */
1863 NULL
, /* nb_inplace_and */
1864 NULL
, /* nb_inplace_xor */
1865 NULL
, /* nb_inplace_or */
1866 NULL
, /* nb_floor_divide */
1867 valpy_divide
, /* nb_true_divide */
1868 NULL
, /* nb_inplace_floor_divide */
1869 NULL
, /* nb_inplace_true_divide */
1870 #ifndef HAVE_LIBPYTHON2_4
1871 /* This was added in Python 2.5. */
1872 valpy_long
, /* nb_index */
1873 #endif /* HAVE_LIBPYTHON2_4 */
1876 static PyMappingMethods value_object_as_mapping
= {
1882 PyTypeObject value_object_type
= {
1883 PyVarObject_HEAD_INIT (NULL
, 0)
1884 "gdb.Value", /*tp_name*/
1885 sizeof (value_object
), /*tp_basicsize*/
1887 valpy_dealloc
, /*tp_dealloc*/
1893 &value_object_as_number
, /*tp_as_number*/
1894 0, /*tp_as_sequence*/
1895 &value_object_as_mapping
, /*tp_as_mapping*/
1896 valpy_hash
, /*tp_hash*/
1897 valpy_call
, /*tp_call*/
1898 valpy_str
, /*tp_str*/
1902 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
1903 | Py_TPFLAGS_BASETYPE
, /*tp_flags*/
1904 "GDB value object", /* tp_doc */
1905 0, /* tp_traverse */
1907 valpy_richcompare
, /* tp_richcompare */
1908 0, /* tp_weaklistoffset */
1910 0, /* tp_iternext */
1911 value_object_methods
, /* tp_methods */
1913 value_object_getset
, /* tp_getset */
1916 0, /* tp_descr_get */
1917 0, /* tp_descr_set */
1918 0, /* tp_dictoffset */
1921 valpy_new
/* tp_new */