1 /* Python interface to values.
3 Copyright (C) 2008-2014 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/>. */
23 #include "exceptions.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 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 volatile struct gdb_exception except;
177 PyObject *result = NULL;
179 TRY_CATCH (except, RETURN_MASK_ALL)
181 struct value *res_val;
182 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
184 res_val = value_ind (((value_object *) self)->value);
185 result = value_to_value_object (res_val);
186 do_cleanups (cleanup);
188 GDB_PY_HANDLE_EXCEPTION (except);
193 /* Given a value of a pointer type or a reference type, return the value
194 referenced. The difference between this function and valpy_dereference is
195 that the latter applies * unary operator to a value, which need not always
196 result in the value referenced. For example, for a value which is a reference
197 to an 'int' pointer ('int *'), valpy_dereference will result in a value of
198 type 'int' while valpy_referenced_value will result in a value of type
202 valpy_referenced_value (PyObject *self, PyObject *args)
204 volatile struct gdb_exception except;
205 PyObject *result = NULL;
207 TRY_CATCH (except, RETURN_MASK_ALL)
209 struct value *self_val, *res_val;
210 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
212 self_val = ((value_object *) self)->value;
213 switch (TYPE_CODE (check_typedef (value_type (self_val))))
216 res_val = value_ind (self_val);
219 res_val = coerce_ref (self_val);
222 error(_("Trying to get the referenced value from a value which is "
223 "neither a pointer nor a reference."));
226 result = value_to_value_object (res_val);
227 do_cleanups (cleanup);
229 GDB_PY_HANDLE_EXCEPTION (except);
234 /* Return "&value". */
236 valpy_get_address (PyObject *self, void *closure)
238 value_object *val_obj = (value_object *) self;
239 volatile struct gdb_exception except;
241 if (!val_obj->address)
243 TRY_CATCH (except, RETURN_MASK_ALL)
245 struct value *res_val;
246 struct cleanup *cleanup
247 = make_cleanup_value_free_to_mark (value_mark ());
249 res_val = value_addr (val_obj->value);
250 val_obj->address = value_to_value_object (res_val);
251 do_cleanups (cleanup);
253 if (except.reason < 0)
255 val_obj->address = Py_None;
260 Py_XINCREF (val_obj->address);
262 return val_obj->address;
265 /* Return type of the value. */
267 valpy_get_type (PyObject *self, void *closure)
269 value_object *obj = (value_object *) self;
273 obj->type = type_to_type_object (value_type (obj->value));
277 Py_INCREF (obj->type);
281 /* Return dynamic type of the value. */
284 valpy_get_dynamic_type (PyObject *self, void *closure)
286 value_object *obj = (value_object *) self;
287 volatile struct gdb_exception except;
288 struct type *type = NULL;
290 if (obj->dynamic_type != NULL)
292 Py_INCREF (obj->dynamic_type);
293 return obj->dynamic_type;
296 TRY_CATCH (except, RETURN_MASK_ALL)
298 struct value *val = obj->value;
299 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
301 type = value_type (val);
302 CHECK_TYPEDEF (type);
304 if (((TYPE_CODE (type) == TYPE_CODE_PTR)
305 || (TYPE_CODE (type) == TYPE_CODE_REF))
306 && (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_CLASS))
308 struct value *target;
309 int was_pointer = TYPE_CODE (type) == TYPE_CODE_PTR;
312 target = value_ind (val);
314 target = coerce_ref (val);
315 type = value_rtti_type (target, NULL, NULL, NULL);
320 type = lookup_pointer_type (type);
322 type = lookup_reference_type (type);
325 else if (TYPE_CODE (type) == TYPE_CODE_CLASS)
326 type = value_rtti_type (val, NULL, NULL, NULL);
329 /* Re-use object's static type. */
333 do_cleanups (cleanup);
335 GDB_PY_HANDLE_EXCEPTION (except);
338 obj->dynamic_type = valpy_get_type (self, NULL);
340 obj->dynamic_type = type_to_type_object (type);
342 Py_XINCREF (obj->dynamic_type);
343 return obj->dynamic_type;
346 /* Implementation of gdb.Value.lazy_string ([encoding] [, length]) ->
347 string. Return a PyObject representing a lazy_string_object type.
348 A lazy string is a pointer to a string with an optional encoding and
349 length. If ENCODING is not given, encoding is set to None. If an
350 ENCODING is provided the encoding parameter is set to ENCODING, but
351 the string is not encoded. If LENGTH is provided then the length
352 parameter is set to LENGTH, otherwise length will be set to -1 (first
353 null of appropriate with). */
355 valpy_lazy_string (PyObject *self, PyObject *args, PyObject *kw)
357 gdb_py_longest length = -1;
358 struct value *value = ((value_object *) self)->value;
359 const char *user_encoding = NULL;
360 static char *keywords[] = { "encoding", "length", NULL };
361 PyObject *str_obj = NULL;
362 volatile struct gdb_exception except;
364 if (!PyArg_ParseTupleAndKeywords (args, kw, "|s" GDB_PY_LL_ARG, keywords,
365 &user_encoding, &length))
368 TRY_CATCH (except, RETURN_MASK_ALL)
370 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
372 if (TYPE_CODE (value_type (value)) == TYPE_CODE_PTR)
373 value = value_ind (value);
375 str_obj = gdbpy_create_lazy_string_object (value_address (value), length,
379 do_cleanups (cleanup);
381 GDB_PY_HANDLE_EXCEPTION (except);
386 /* Implementation of gdb.Value.string ([encoding] [, errors]
387 [, length]) -> string. Return Unicode string with value contents.
388 If ENCODING is not given, the string is assumed to be encoded in
389 the target's charset. If LENGTH is provided, only fetch string to
390 the length provided. */
393 valpy_string (PyObject *self, PyObject *args, PyObject *kw)
397 struct value *value = ((value_object *) self)->value;
398 volatile struct gdb_exception except;
400 const char *encoding = NULL;
401 const char *errors = NULL;
402 const char *user_encoding = NULL;
403 const char *la_encoding = NULL;
404 struct type *char_type;
405 static char *keywords[] = { "encoding", "errors", "length", NULL };
407 if (!PyArg_ParseTupleAndKeywords (args, kw, "|ssi", keywords,
408 &user_encoding, &errors, &length))
411 TRY_CATCH (except, RETURN_MASK_ALL)
413 LA_GET_STRING (value, &buffer, &length, &char_type, &la_encoding);
415 GDB_PY_HANDLE_EXCEPTION (except);
417 encoding = (user_encoding && *user_encoding) ? user_encoding : la_encoding;
418 unicode = PyUnicode_Decode ((const char *) buffer,
419 length * TYPE_LENGTH (char_type),
426 /* A helper function that implements the various cast operators. */
429 valpy_do_cast (PyObject *self, PyObject *args, enum exp_opcode op)
431 PyObject *type_obj, *result = NULL;
433 volatile struct gdb_exception except;
435 if (! PyArg_ParseTuple (args, "O", &type_obj))
438 type = type_object_to_type (type_obj);
441 PyErr_SetString (PyExc_RuntimeError,
442 _("Argument must be a type."));
446 TRY_CATCH (except, RETURN_MASK_ALL)
448 struct value *val = ((value_object *) self)->value;
449 struct value *res_val;
450 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
452 if (op == UNOP_DYNAMIC_CAST)
453 res_val = value_dynamic_cast (type, val);
454 else if (op == UNOP_REINTERPRET_CAST)
455 res_val = value_reinterpret_cast (type, val);
458 gdb_assert (op == UNOP_CAST);
459 res_val = value_cast (type, val);
462 result = value_to_value_object (res_val);
463 do_cleanups (cleanup);
465 GDB_PY_HANDLE_EXCEPTION (except);
470 /* Implementation of the "cast" method. */
473 valpy_cast (PyObject *self, PyObject *args)
475 return valpy_do_cast (self, args, UNOP_CAST);
478 /* Implementation of the "dynamic_cast" method. */
481 valpy_dynamic_cast (PyObject *self, PyObject *args)
483 return valpy_do_cast (self, args, UNOP_DYNAMIC_CAST);
486 /* Implementation of the "reinterpret_cast" method. */
489 valpy_reinterpret_cast (PyObject *self, PyObject *args)
491 return valpy_do_cast (self, args, UNOP_REINTERPRET_CAST);
495 valpy_length (PyObject *self)
497 /* We don't support getting the number of elements in a struct / class. */
498 PyErr_SetString (PyExc_NotImplementedError,
499 _("Invalid operation on gdb.Value."));
503 /* Return 1 if the gdb.Field object FIELD is present in the value V.
504 Returns 0 otherwise. If any Python error occurs, -1 is returned. */
507 value_has_field (struct value *v, PyObject *field)
509 struct type *parent_type, *val_type;
510 enum type_code type_code;
511 PyObject *type_object = PyObject_GetAttrString (field, "parent_type");
512 volatile struct gdb_exception except;
515 if (type_object == NULL)
518 parent_type = type_object_to_type (type_object);
519 Py_DECREF (type_object);
520 if (parent_type == NULL)
522 PyErr_SetString (PyExc_TypeError,
523 _("'parent_type' attribute of gdb.Field object is not a"
524 "gdb.Type object."));
528 TRY_CATCH (except, RETURN_MASK_ALL)
530 val_type = value_type (v);
531 val_type = check_typedef (val_type);
532 if (TYPE_CODE (val_type) == TYPE_CODE_REF
533 || TYPE_CODE (val_type) == TYPE_CODE_PTR)
534 val_type = check_typedef (TYPE_TARGET_TYPE (val_type));
536 type_code = TYPE_CODE (val_type);
537 if ((type_code == TYPE_CODE_STRUCT || type_code == TYPE_CODE_UNION)
538 && types_equal (val_type, parent_type))
543 GDB_PY_SET_HANDLE_EXCEPTION (except);
548 /* Return the value of a flag FLAG_NAME in a gdb.Field object FIELD.
549 Returns 1 if the flag value is true, 0 if it is false, and -1 if
550 a Python error occurs. */
553 get_field_flag (PyObject *field, const char *flag_name)
556 PyObject *flag_object = PyObject_GetAttrString (field, flag_name);
558 if (flag_object == NULL)
561 flag_value = PyObject_IsTrue (flag_object);
562 Py_DECREF (flag_object);
567 /* Return the "type" attribute of a gdb.Field object.
568 Returns NULL on error, with a Python exception set. */
571 get_field_type (PyObject *field)
573 PyObject *ftype_obj = PyObject_GetAttrString (field, "type");
576 if (ftype_obj == NULL)
578 ftype = type_object_to_type (ftype_obj);
579 Py_DECREF (ftype_obj);
581 PyErr_SetString (PyExc_TypeError,
582 _("'type' attribute of gdb.Field object is not a "
583 "gdb.Type object."));
588 /* Given string name or a gdb.Field object corresponding to an element inside
589 a structure, return its value object. Returns NULL on error, with a python
593 valpy_getitem (PyObject *self, PyObject *key)
595 value_object *self_value = (value_object *) self;
597 struct type *base_class_type = NULL, *field_type = NULL;
599 volatile struct gdb_exception except;
600 PyObject *result = NULL;
602 if (gdbpy_is_string (key))
604 field = python_string_to_host_string (key);
608 else if (gdbpy_is_field (key))
610 int is_base_class, valid_field;
612 valid_field = value_has_field (self_value->value, key);
615 else if (valid_field == 0)
617 PyErr_SetString (PyExc_TypeError,
618 _("Invalid lookup for a field not contained in "
624 is_base_class = get_field_flag (key, "is_base_class");
625 if (is_base_class < 0)
627 else if (is_base_class > 0)
629 base_class_type = get_field_type (key);
630 if (base_class_type == NULL)
635 PyObject *name_obj = PyObject_GetAttrString (key, "name");
637 if (name_obj == NULL)
640 if (name_obj != Py_None)
642 field = python_string_to_host_string (name_obj);
643 Py_DECREF (name_obj);
649 PyObject *bitpos_obj;
652 Py_DECREF (name_obj);
654 if (!PyObject_HasAttrString (key, "bitpos"))
656 PyErr_SetString (PyExc_AttributeError,
657 _("gdb.Field object has no name and no "
658 "'bitpos' attribute."));
662 bitpos_obj = PyObject_GetAttrString (key, "bitpos");
663 if (bitpos_obj == NULL)
665 valid = gdb_py_int_as_long (bitpos_obj, &bitpos);
666 Py_DECREF (bitpos_obj);
670 field_type = get_field_type (key);
671 if (field_type == NULL)
677 TRY_CATCH (except, RETURN_MASK_ALL)
679 struct value *tmp = self_value->value;
680 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
681 struct value *res_val = NULL;
684 res_val = value_struct_elt (&tmp, NULL, field, 0, NULL);
685 else if (bitpos >= 0)
686 res_val = value_struct_elt_bitpos (&tmp, bitpos, field_type,
687 "struct/class/union");
688 else if (base_class_type != NULL)
690 struct type *val_type;
692 val_type = check_typedef (value_type (tmp));
693 if (TYPE_CODE (val_type) == TYPE_CODE_PTR)
694 res_val = value_cast (lookup_pointer_type (base_class_type), tmp);
695 else if (TYPE_CODE (val_type) == TYPE_CODE_REF)
696 res_val = value_cast (lookup_reference_type (base_class_type), tmp);
698 res_val = value_cast (base_class_type, tmp);
702 /* Assume we are attempting an array access, and let the
703 value code throw an exception if the index has an invalid
705 struct value *idx = convert_value_from_python (key);
709 /* Check the value's type is something that can be accessed via
713 tmp = coerce_ref (tmp);
714 type = check_typedef (value_type (tmp));
715 if (TYPE_CODE (type) != TYPE_CODE_ARRAY
716 && TYPE_CODE (type) != TYPE_CODE_PTR)
717 error (_("Cannot subscript requested type."));
719 res_val = value_subscript (tmp, value_as_long (idx));
724 result = value_to_value_object (res_val);
725 do_cleanups (cleanup);
729 GDB_PY_HANDLE_EXCEPTION (except);
735 valpy_setitem (PyObject *self, PyObject *key, PyObject *value)
737 PyErr_Format (PyExc_NotImplementedError,
738 _("Setting of struct elements is not currently supported."));
742 /* Called by the Python interpreter to perform an inferior function
743 call on the value. Returns NULL on error, with a python exception set. */
745 valpy_call (PyObject *self, PyObject *args, PyObject *keywords)
747 Py_ssize_t args_count;
748 volatile struct gdb_exception except;
749 struct value *function = ((value_object *) self)->value;
750 struct value **vargs = NULL;
751 struct type *ftype = NULL;
752 struct value *mark = value_mark ();
753 PyObject *result = NULL;
755 TRY_CATCH (except, RETURN_MASK_ALL)
757 ftype = check_typedef (value_type (function));
759 GDB_PY_HANDLE_EXCEPTION (except);
761 if (TYPE_CODE (ftype) != TYPE_CODE_FUNC)
763 PyErr_SetString (PyExc_RuntimeError,
764 _("Value is not callable (not TYPE_CODE_FUNC)."));
768 if (! PyTuple_Check (args))
770 PyErr_SetString (PyExc_TypeError,
771 _("Inferior arguments must be provided in a tuple."));
775 args_count = PyTuple_Size (args);
780 vargs = alloca (sizeof (struct value *) * args_count);
781 for (i = 0; i < args_count; i++)
783 PyObject *item = PyTuple_GetItem (args, i);
788 vargs[i] = convert_value_from_python (item);
789 if (vargs[i] == NULL)
794 TRY_CATCH (except, RETURN_MASK_ALL)
796 struct cleanup *cleanup = make_cleanup_value_free_to_mark (mark);
797 struct value *return_value;
799 return_value = call_function_by_hand (function, args_count, vargs);
800 result = value_to_value_object (return_value);
801 do_cleanups (cleanup);
803 GDB_PY_HANDLE_EXCEPTION (except);
808 /* Called by the Python interpreter to obtain string representation
811 valpy_str (PyObject *self)
815 struct value_print_options opts;
816 volatile struct gdb_exception except;
818 get_user_print_options (&opts);
821 TRY_CATCH (except, RETURN_MASK_ALL)
823 struct ui_file *stb = mem_fileopen ();
824 struct cleanup *old_chain = make_cleanup_ui_file_delete (stb);
826 common_val_print (((value_object *) self)->value, stb, 0,
827 &opts, python_language);
828 s = ui_file_xstrdup (stb, NULL);
830 do_cleanups (old_chain);
832 GDB_PY_HANDLE_EXCEPTION (except);
834 result = PyUnicode_Decode (s, strlen (s), host_charset (), NULL);
840 /* Implements gdb.Value.is_optimized_out. */
842 valpy_get_is_optimized_out (PyObject *self, void *closure)
844 struct value *value = ((value_object *) self)->value;
846 volatile struct gdb_exception except;
848 TRY_CATCH (except, RETURN_MASK_ALL)
850 opt = value_optimized_out (value);
852 GDB_PY_HANDLE_EXCEPTION (except);
860 /* Implements gdb.Value.is_lazy. */
862 valpy_get_is_lazy (PyObject *self, void *closure)
864 struct value *value = ((value_object *) self)->value;
866 volatile struct gdb_exception except;
868 TRY_CATCH (except, RETURN_MASK_ALL)
870 opt = value_lazy (value);
872 GDB_PY_HANDLE_EXCEPTION (except);
880 /* Implements gdb.Value.fetch_lazy (). */
882 valpy_fetch_lazy (PyObject *self, PyObject *args)
884 struct value *value = ((value_object *) self)->value;
885 volatile struct gdb_exception except;
887 TRY_CATCH (except, RETURN_MASK_ALL)
889 if (value_lazy (value))
890 value_fetch_lazy (value);
892 GDB_PY_HANDLE_EXCEPTION (except);
897 /* Calculate and return the address of the PyObject as the value of
898 the builtin __hash__ call. */
900 valpy_hash (PyObject *self)
902 return (long) (intptr_t) self;
920 /* If TYPE is a reference, return the target; otherwise return TYPE. */
921 #define STRIP_REFERENCE(TYPE) \
922 ((TYPE_CODE (TYPE) == TYPE_CODE_REF) ? (TYPE_TARGET_TYPE (TYPE)) : (TYPE))
924 /* Returns a value object which is the result of applying the operation
925 specified by OPCODE to the given arguments. Returns NULL on error, with
926 a python exception set. */
928 valpy_binop (enum valpy_opcode opcode, PyObject *self, PyObject *other)
930 volatile struct gdb_exception except;
931 PyObject *result = NULL;
933 TRY_CATCH (except, RETURN_MASK_ALL)
935 struct value *arg1, *arg2;
936 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
937 struct value *res_val = NULL;
938 enum exp_opcode op = OP_NULL;
941 /* If the gdb.Value object is the second operand, then it will be passed
942 to us as the OTHER argument, and SELF will be an entirely different
943 kind of object, altogether. Because of this, we can't assume self is
944 a gdb.Value object and need to convert it from python as well. */
945 arg1 = convert_value_from_python (self);
948 do_cleanups (cleanup);
952 arg2 = convert_value_from_python (other);
955 do_cleanups (cleanup);
963 struct type *ltype = value_type (arg1);
964 struct type *rtype = value_type (arg2);
966 CHECK_TYPEDEF (ltype);
967 ltype = STRIP_REFERENCE (ltype);
968 CHECK_TYPEDEF (rtype);
969 rtype = STRIP_REFERENCE (rtype);
972 if (TYPE_CODE (ltype) == TYPE_CODE_PTR
973 && is_integral_type (rtype))
974 res_val = value_ptradd (arg1, value_as_long (arg2));
975 else if (TYPE_CODE (rtype) == TYPE_CODE_PTR
976 && is_integral_type (ltype))
977 res_val = value_ptradd (arg2, value_as_long (arg1));
987 struct type *ltype = value_type (arg1);
988 struct type *rtype = value_type (arg2);
990 CHECK_TYPEDEF (ltype);
991 ltype = STRIP_REFERENCE (ltype);
992 CHECK_TYPEDEF (rtype);
993 rtype = STRIP_REFERENCE (rtype);
996 if (TYPE_CODE (ltype) == TYPE_CODE_PTR
997 && TYPE_CODE (rtype) == TYPE_CODE_PTR)
998 /* A ptrdiff_t for the target would be preferable here. */
999 res_val = value_from_longest (builtin_type_pyint,
1000 value_ptrdiff (arg1, arg2));
1001 else if (TYPE_CODE (ltype) == TYPE_CODE_PTR
1002 && is_integral_type (rtype))
1003 res_val = value_ptradd (arg1, - value_as_long (arg2));
1030 op = BINOP_BITWISE_AND;
1033 op = BINOP_BITWISE_IOR;
1036 op = BINOP_BITWISE_XOR;
1042 if (binop_user_defined_p (op, arg1, arg2))
1043 res_val = value_x_binop (arg1, arg2, op, OP_NULL, EVAL_NORMAL);
1045 res_val = value_binop (arg1, arg2, op);
1049 result = value_to_value_object (res_val);
1051 do_cleanups (cleanup);
1053 GDB_PY_HANDLE_EXCEPTION (except);
1059 valpy_add (PyObject *self, PyObject *other)
1061 return valpy_binop (VALPY_ADD, self, other);
1065 valpy_subtract (PyObject *self, PyObject *other)
1067 return valpy_binop (VALPY_SUB, self, other);
1071 valpy_multiply (PyObject *self, PyObject *other)
1073 return valpy_binop (VALPY_MUL, self, other);
1077 valpy_divide (PyObject *self, PyObject *other)
1079 return valpy_binop (VALPY_DIV, self, other);
1083 valpy_remainder (PyObject *self, PyObject *other)
1085 return valpy_binop (VALPY_REM, self, other);
1089 valpy_power (PyObject *self, PyObject *other, PyObject *unused)
1091 /* We don't support the ternary form of pow. I don't know how to express
1092 that, so let's just throw NotImplementedError to at least do something
1094 if (unused != Py_None)
1096 PyErr_SetString (PyExc_NotImplementedError,
1097 "Invalid operation on gdb.Value.");
1101 return valpy_binop (VALPY_POW, self, other);
1105 valpy_negative (PyObject *self)
1107 volatile struct gdb_exception except;
1108 PyObject *result = NULL;
1110 TRY_CATCH (except, RETURN_MASK_ALL)
1112 /* Perhaps overkill, but consistency has some virtue. */
1113 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
1116 val = value_neg (((value_object *) self)->value);
1117 result = value_to_value_object (val);
1118 do_cleanups (cleanup);
1120 GDB_PY_HANDLE_EXCEPTION (except);
1126 valpy_positive (PyObject *self)
1128 return value_to_value_object (((value_object *) self)->value);
1132 valpy_absolute (PyObject *self)
1134 struct value *value = ((value_object *) self)->value;
1135 volatile struct gdb_exception except;
1138 TRY_CATCH (except, RETURN_MASK_ALL)
1140 struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
1142 if (value_less (value, value_zero (value_type (value), not_lval)))
1145 do_cleanups (cleanup);
1147 GDB_PY_HANDLE_EXCEPTION (except);
1150 return valpy_positive (self);
1152 return valpy_negative (self);
1155 /* Implements boolean evaluation of gdb.Value. */
1157 valpy_nonzero (PyObject *self)
1159 volatile struct gdb_exception except;
1160 value_object *self_value = (value_object *) self;
1162 int nonzero = 0; /* Appease GCC warning. */
1164 TRY_CATCH (except, RETURN_MASK_ALL)
1166 type = check_typedef (value_type (self_value->value));
1168 if (is_integral_type (type) || TYPE_CODE (type) == TYPE_CODE_PTR)
1169 nonzero = !!value_as_long (self_value->value);
1170 else if (TYPE_CODE (type) == TYPE_CODE_FLT)
1171 nonzero = value_as_double (self_value->value) != 0;
1172 else if (TYPE_CODE (type) == TYPE_CODE_DECFLOAT)
1173 nonzero = !decimal_is_zero (value_contents (self_value->value),
1175 gdbarch_byte_order (get_type_arch (type)));
1177 /* All other values are True. */
1180 /* This is not documented in the Python documentation, but if this
1181 function fails, return -1 as slot_nb_nonzero does (the default
1182 Python nonzero function). */
1183 GDB_PY_SET_HANDLE_EXCEPTION (except);
1188 /* Implements ~ for value objects. */
1190 valpy_invert (PyObject *self)
1192 struct value *val = NULL;
1193 volatile struct gdb_exception except;
1195 TRY_CATCH (except, RETURN_MASK_ALL)
1197 val = value_complement (((value_object *) self)->value);
1199 GDB_PY_HANDLE_EXCEPTION (except);
1201 return value_to_value_object (val);
1204 /* Implements left shift for value objects. */
1206 valpy_lsh (PyObject *self, PyObject *other)
1208 return valpy_binop (VALPY_LSH, self, other);
1211 /* Implements right shift for value objects. */
1213 valpy_rsh (PyObject *self, PyObject *other)
1215 return valpy_binop (VALPY_RSH, self, other);
1218 /* Implements bitwise and for value objects. */
1220 valpy_and (PyObject *self, PyObject *other)
1222 return valpy_binop (VALPY_BITAND, self, other);
1225 /* Implements bitwise or for value objects. */
1227 valpy_or (PyObject *self, PyObject *other)
1229 return valpy_binop (VALPY_BITOR, self, other);
1232 /* Implements bitwise xor for value objects. */
1234 valpy_xor (PyObject *self, PyObject *other)
1236 return valpy_binop (VALPY_BITXOR, self, other);
1239 /* Implements comparison operations for value objects. Returns NULL on error,
1240 with a python exception set. */
1242 valpy_richcompare (PyObject *self, PyObject *other, int op)
1245 volatile struct gdb_exception except;
1247 if (other == Py_None)
1248 /* Comparing with None is special. From what I can tell, in Python
1249 None is smaller than anything else. */
1261 PyErr_SetString (PyExc_NotImplementedError,
1262 _("Invalid operation on gdb.Value."));
1266 TRY_CATCH (except, RETURN_MASK_ALL)
1268 struct value *value_other, *mark = value_mark ();
1269 struct cleanup *cleanup;
1271 value_other = convert_value_from_python (other);
1272 if (value_other == NULL)
1278 cleanup = make_cleanup_value_free_to_mark (mark);
1282 result = value_less (((value_object *) self)->value, value_other);
1285 result = value_less (((value_object *) self)->value, value_other)
1286 || value_equal (((value_object *) self)->value, value_other);
1289 result = value_equal (((value_object *) self)->value, value_other);
1292 result = !value_equal (((value_object *) self)->value, value_other);
1295 result = value_less (value_other, ((value_object *) self)->value);
1298 result = value_less (value_other, ((value_object *) self)->value)
1299 || value_equal (((value_object *) self)->value, value_other);
1303 PyErr_SetString (PyExc_NotImplementedError,
1304 _("Invalid operation on gdb.Value."));
1309 do_cleanups (cleanup);
1311 GDB_PY_HANDLE_EXCEPTION (except);
1313 /* In this case, the Python exception has already been set. */
1324 /* Implements conversion to int. */
1326 valpy_int (PyObject *self)
1328 struct value *value = ((value_object *) self)->value;
1329 struct type *type = value_type (value);
1331 volatile struct gdb_exception except;
1333 TRY_CATCH (except, RETURN_MASK_ALL)
1335 if (!is_integral_type (type))
1336 error (_("Cannot convert value to int."));
1338 l = value_as_long (value);
1340 GDB_PY_HANDLE_EXCEPTION (except);
1342 return gdb_py_object_from_longest (l);
1346 /* Implements conversion to long. */
1348 valpy_long (PyObject *self)
1350 struct value *value = ((value_object *) self)->value;
1351 struct type *type = value_type (value);
1353 volatile struct gdb_exception except;
1355 TRY_CATCH (except, RETURN_MASK_ALL)
1357 CHECK_TYPEDEF (type);
1359 if (!is_integral_type (type)
1360 && TYPE_CODE (type) != TYPE_CODE_PTR)
1361 error (_("Cannot convert value to long."));
1363 l = value_as_long (value);
1365 GDB_PY_HANDLE_EXCEPTION (except);
1367 return gdb_py_long_from_longest (l);
1370 /* Implements conversion to float. */
1372 valpy_float (PyObject *self)
1374 struct value *value = ((value_object *) self)->value;
1375 struct type *type = value_type (value);
1377 volatile struct gdb_exception except;
1379 TRY_CATCH (except, RETURN_MASK_ALL)
1381 CHECK_TYPEDEF (type);
1383 if (TYPE_CODE (type) != TYPE_CODE_FLT)
1384 error (_("Cannot convert value to float."));
1386 d = value_as_double (value);
1388 GDB_PY_HANDLE_EXCEPTION (except);
1390 return PyFloat_FromDouble (d);
1393 /* Returns an object for a value which is released from the all_values chain,
1394 so its lifetime is not bound to the execution of a command. */
1396 value_to_value_object (struct value *val)
1398 value_object *val_obj;
1400 val_obj = PyObject_New (value_object, &value_object_type);
1401 if (val_obj != NULL)
1403 val_obj->value = val;
1404 release_value_or_incref (val);
1405 val_obj->address = NULL;
1406 val_obj->type = NULL;
1407 val_obj->dynamic_type = NULL;
1408 note_value (val_obj);
1411 return (PyObject *) val_obj;
1414 /* Returns a borrowed reference to the struct value corresponding to
1415 the given value object. */
1417 value_object_to_value (PyObject *self)
1421 if (! PyObject_TypeCheck (self, &value_object_type))
1423 real = (value_object *) self;
1427 /* Try to convert a Python value to a gdb value. If the value cannot
1428 be converted, set a Python exception and return NULL. Returns a
1429 reference to a new value on the all_values chain. */
1432 convert_value_from_python (PyObject *obj)
1434 struct value *value = NULL; /* -Wall */
1435 volatile struct gdb_exception except;
1438 gdb_assert (obj != NULL);
1440 TRY_CATCH (except, RETURN_MASK_ALL)
1442 if (PyBool_Check (obj))
1444 cmp = PyObject_IsTrue (obj);
1446 value = value_from_longest (builtin_type_pybool, cmp);
1448 /* Make a long logic check first. In Python 3.x, internally,
1449 all integers are represented as longs. In Python 2.x, there
1450 is still a differentiation internally between a PyInt and a
1451 PyLong. Explicitly do this long check conversion first. In
1452 GDB, for Python 3.x, we #ifdef PyInt = PyLong. This check has
1453 to be done first to ensure we do not lose information in the
1454 conversion process. */
1455 else if (PyLong_Check (obj))
1457 LONGEST l = PyLong_AsLongLong (obj);
1459 if (PyErr_Occurred ())
1461 /* If the error was an overflow, we can try converting to
1462 ULONGEST instead. */
1463 if (PyErr_ExceptionMatches (PyExc_OverflowError))
1465 PyObject *etype, *evalue, *etraceback, *zero;
1467 PyErr_Fetch (&etype, &evalue, &etraceback);
1468 zero = PyInt_FromLong (0);
1470 /* Check whether obj is positive. */
1471 if (PyObject_RichCompareBool (obj, zero, Py_GT) > 0)
1475 ul = PyLong_AsUnsignedLongLong (obj);
1476 if (! PyErr_Occurred ())
1477 value = value_from_ulongest (builtin_type_upylong, ul);
1480 /* There's nothing we can do. */
1481 PyErr_Restore (etype, evalue, etraceback);
1487 value = value_from_longest (builtin_type_pylong, l);
1489 else if (PyInt_Check (obj))
1491 long l = PyInt_AsLong (obj);
1493 if (! PyErr_Occurred ())
1494 value = value_from_longest (builtin_type_pyint, l);
1496 else if (PyFloat_Check (obj))
1498 double d = PyFloat_AsDouble (obj);
1500 if (! PyErr_Occurred ())
1501 value = value_from_double (builtin_type_pyfloat, d);
1503 else if (gdbpy_is_string (obj))
1507 s = python_string_to_target_string (obj);
1510 struct cleanup *old;
1512 old = make_cleanup (xfree, s);
1513 value = value_cstring (s, strlen (s), builtin_type_pychar);
1517 else if (PyObject_TypeCheck (obj, &value_object_type))
1518 value = value_copy (((value_object *) obj)->value);
1519 else if (gdbpy_is_lazy_string (obj))
1523 result = PyObject_CallMethodObjArgs (obj, gdbpy_value_cst, NULL);
1524 value = value_copy (((value_object *) result)->value);
1528 PyErr_Format (PyExc_TypeError,
1529 _("Could not convert Python object: %S."), obj);
1531 PyErr_Format (PyExc_TypeError,
1532 _("Could not convert Python object: %s."),
1533 PyString_AsString (PyObject_Str (obj)));
1536 if (except.reason < 0)
1538 PyErr_Format (except.reason == RETURN_QUIT
1539 ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
1540 "%s", except.message);
1547 /* Returns value object in the ARGth position in GDB's history. */
1549 gdbpy_history (PyObject *self, PyObject *args)
1552 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
1553 volatile struct gdb_exception except;
1555 if (!PyArg_ParseTuple (args, "i", &i))
1558 TRY_CATCH (except, RETURN_MASK_ALL)
1560 res_val = access_value_history (i);
1562 GDB_PY_HANDLE_EXCEPTION (except);
1564 return value_to_value_object (res_val);
1567 /* Returns 1 in OBJ is a gdb.Value object, 0 otherwise. */
1570 gdbpy_is_value_object (PyObject *obj)
1572 return PyObject_TypeCheck (obj, &value_object_type);
1576 gdbpy_initialize_values (void)
1578 if (PyType_Ready (&value_object_type) < 0)
1581 return gdb_pymodule_addobject (gdb_module, "Value",
1582 (PyObject *) &value_object_type);
1587 static PyGetSetDef value_object_getset[] = {
1588 { "address", valpy_get_address, NULL, "The address of the value.",
1590 { "is_optimized_out", valpy_get_is_optimized_out, NULL,
1591 "Boolean telling whether the value is optimized "
1592 "out (i.e., not available).",
1594 { "type", valpy_get_type, NULL, "Type of the value.", NULL },
1595 { "dynamic_type", valpy_get_dynamic_type, NULL,
1596 "Dynamic type of the value.", NULL },
1597 { "is_lazy", valpy_get_is_lazy, NULL,
1598 "Boolean telling whether the value is lazy (not fetched yet\n\
1599 from the inferior). A lazy value is fetched when needed, or when\n\
1600 the \"fetch_lazy()\" method is called.", NULL },
1601 {NULL} /* Sentinel */
1604 static PyMethodDef value_object_methods[] = {
1605 { "cast", valpy_cast, METH_VARARGS, "Cast the value to the supplied type." },
1606 { "dynamic_cast", valpy_dynamic_cast, METH_VARARGS,
1607 "dynamic_cast (gdb.Type) -> gdb.Value\n\
1608 Cast the value to the supplied type, as if by the C++ dynamic_cast operator."
1610 { "reinterpret_cast", valpy_reinterpret_cast, METH_VARARGS,
1611 "reinterpret_cast (gdb.Type) -> gdb.Value\n\
1612 Cast the value to the supplied type, as if by the C++\n\
1613 reinterpret_cast operator."
1615 { "dereference", valpy_dereference, METH_NOARGS, "Dereferences the value." },
1616 { "referenced_value", valpy_referenced_value, METH_NOARGS,
1617 "Return the value referenced by a TYPE_CODE_REF or TYPE_CODE_PTR value." },
1618 { "lazy_string", (PyCFunction) valpy_lazy_string,
1619 METH_VARARGS | METH_KEYWORDS,
1620 "lazy_string ([encoding] [, length]) -> lazy_string\n\
1621 Return a lazy string representation of the value." },
1622 { "string", (PyCFunction) valpy_string, METH_VARARGS | METH_KEYWORDS,
1623 "string ([encoding] [, errors] [, length]) -> string\n\
1624 Return Unicode string representation of the value." },
1625 { "fetch_lazy", valpy_fetch_lazy, METH_NOARGS,
1626 "Fetches the value from the inferior, if it was lazy." },
1627 {NULL} /* Sentinel */
1630 static PyNumberMethods value_object_as_number = {
1638 NULL, /* nb_divmod */
1639 valpy_power, /* nb_power */
1640 valpy_negative, /* nb_negative */
1641 valpy_positive, /* nb_positive */
1642 valpy_absolute, /* nb_absolute */
1643 valpy_nonzero, /* nb_nonzero */
1644 valpy_invert, /* nb_invert */
1645 valpy_lsh, /* nb_lshift */
1646 valpy_rsh, /* nb_rshift */
1647 valpy_and, /* nb_and */
1648 valpy_xor, /* nb_xor */
1649 valpy_or, /* nb_or */
1651 valpy_long, /* nb_int */
1652 NULL, /* reserved */
1654 NULL, /* nb_coerce */
1655 valpy_int, /* nb_int */
1656 valpy_long, /* nb_long */
1658 valpy_float, /* nb_float */
1663 NULL, /* nb_inplace_add */
1664 NULL, /* nb_inplace_subtract */
1665 NULL, /* nb_inplace_multiply */
1666 NULL, /* nb_inplace_remainder */
1667 NULL, /* nb_inplace_power */
1668 NULL, /* nb_inplace_lshift */
1669 NULL, /* nb_inplace_rshift */
1670 NULL, /* nb_inplace_and */
1671 NULL, /* nb_inplace_xor */
1672 NULL, /* nb_inplace_or */
1673 NULL, /* nb_floor_divide */
1674 valpy_divide /* nb_true_divide */
1677 static PyMappingMethods value_object_as_mapping = {
1683 PyTypeObject value_object_type = {
1684 PyVarObject_HEAD_INIT (NULL, 0)
1685 "gdb.Value", /*tp_name*/
1686 sizeof (value_object), /*tp_basicsize*/
1688 valpy_dealloc, /*tp_dealloc*/
1694 &value_object_as_number, /*tp_as_number*/
1695 0, /*tp_as_sequence*/
1696 &value_object_as_mapping, /*tp_as_mapping*/
1697 valpy_hash, /*tp_hash*/
1698 valpy_call, /*tp_call*/
1699 valpy_str, /*tp_str*/
1703 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES
1704 | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1705 "GDB value object", /* tp_doc */
1706 0, /* tp_traverse */
1708 valpy_richcompare, /* tp_richcompare */
1709 0, /* tp_weaklistoffset */
1711 0, /* tp_iternext */
1712 value_object_methods, /* tp_methods */
1714 value_object_getset, /* tp_getset */
1717 0, /* tp_descr_get */
1718 0, /* tp_descr_set */
1719 0, /* tp_dictoffset */
1722 valpy_new /* tp_new */