1 /* Python interface to values.
3 Copyright (C) 2008, 2009 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 "gdb_assert.h"
24 #include "exceptions.h"
29 /* List of all values which are currently exposed to Python. It is
30 maintained so that when an objfile is discarded, preserve_values
31 can copy the values' types if needed. This is declared
32 unconditionally to reduce the number of uses of HAVE_PYTHON in the
34 /* This variable is unnecessarily initialized to NULL in order to
35 work around a linker bug on MacOS. */
36 struct value
*values_in_python
= NULL
;
40 #include "python-internal.h"
42 /* Even though Python scalar types directly map to host types, we use
43 target types here to remain consistent with the the values system in
44 GDB (which uses target arithmetic). */
46 /* Python's integer type corresponds to C's long type. */
47 #define builtin_type_pyint builtin_type (current_gdbarch)->builtin_long
49 /* Python's float type corresponds to C's double type. */
50 #define builtin_type_pyfloat builtin_type (current_gdbarch)->builtin_double
52 /* Python's long type corresponds to C's long long type. */
53 #define builtin_type_pylong builtin_type (current_gdbarch)->builtin_long_long
55 #define builtin_type_pybool \
56 language_bool_type (current_language, current_gdbarch)
64 /* Called by the Python interpreter when deallocating a value object. */
66 valpy_dealloc (PyObject
*obj
)
68 value_object
*self
= (value_object
*) obj
;
70 value_remove_from_list (&values_in_python
, self
->value
);
72 value_free (self
->value
);
75 /* Use braces to appease gcc warning. *sigh* */
77 Py_DECREF (self
->address
);
80 self
->ob_type
->tp_free (self
);
83 /* Called when a new gdb.Value object needs to be allocated. */
85 valpy_new (PyTypeObject
*subtype
, PyObject
*args
, PyObject
*keywords
)
87 struct value
*value
= NULL
; /* Initialize to appease gcc warning. */
88 value_object
*value_obj
;
90 if (PyTuple_Size (args
) != 1)
92 PyErr_SetString (PyExc_TypeError
, _("Value object creation takes only "
97 value_obj
= (value_object
*) subtype
->tp_alloc (subtype
, 1);
98 if (value_obj
== NULL
)
100 PyErr_SetString (PyExc_MemoryError
, _("Could not allocate memory to "
101 "create Value object."));
105 value
= convert_value_from_python (PyTuple_GetItem (args
, 0));
108 subtype
->tp_free (value_obj
);
112 value_obj
->value
= value
;
113 value_obj
->address
= NULL
;
114 release_value (value
);
115 value_prepend_to_list (&values_in_python
, value
);
117 return (PyObject
*) value_obj
;
120 /* Given a value of a pointer type, apply the C unary * operator to it. */
122 valpy_dereference (PyObject
*self
, PyObject
*args
)
124 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
125 volatile struct gdb_exception except
;
127 TRY_CATCH (except
, RETURN_MASK_ALL
)
129 res_val
= value_ind (((value_object
*) self
)->value
);
131 GDB_PY_HANDLE_EXCEPTION (except
);
133 return value_to_value_object (res_val
);
136 /* Return "&value". */
138 valpy_get_address (PyObject
*self
, void *closure
)
140 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
141 value_object
*val_obj
= (value_object
*) self
;
142 volatile struct gdb_exception except
;
144 if (!val_obj
->address
)
146 TRY_CATCH (except
, RETURN_MASK_ALL
)
148 res_val
= value_addr (val_obj
->value
);
150 if (except
.reason
< 0)
152 val_obj
->address
= Py_None
;
156 val_obj
->address
= value_to_value_object (res_val
);
159 Py_INCREF (val_obj
->address
);
161 return val_obj
->address
;
164 /* Implementation of gdb.Value.string ([encoding] [, errors]) -> string
165 Return Unicode string with value contents. If ENCODING is not given,
166 the string is assumed to be encoded in the target's charset. */
168 valpy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
172 struct value
*value
= ((value_object
*) self
)->value
;
173 volatile struct gdb_exception except
;
175 const char *encoding
= NULL
;
176 const char *errors
= NULL
;
177 const char *user_encoding
= NULL
;
178 const char *la_encoding
= NULL
;
179 static char *keywords
[] = { "encoding", "errors" };
181 if (!PyArg_ParseTupleAndKeywords (args
, kw
, "|ss", keywords
,
182 &user_encoding
, &errors
))
185 TRY_CATCH (except
, RETURN_MASK_ALL
)
187 LA_GET_STRING (value
, &buffer
, &length
, &la_encoding
);
189 GDB_PY_HANDLE_EXCEPTION (except
);
191 encoding
= (user_encoding
&& *user_encoding
) ? user_encoding
: la_encoding
;
192 unicode
= PyUnicode_Decode (buffer
, length
, encoding
, errors
);
199 valpy_length (PyObject
*self
)
201 /* We don't support getting the number of elements in a struct / class. */
202 PyErr_SetString (PyExc_NotImplementedError
,
203 "Invalid operation on gdb.Value.");
207 /* Given string name of an element inside structure, return its value
210 valpy_getitem (PyObject
*self
, PyObject
*key
)
212 value_object
*self_value
= (value_object
*) self
;
214 struct value
*idx
= NULL
;
215 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
216 volatile struct gdb_exception except
;
218 if (gdbpy_is_string (key
))
220 field
= python_string_to_host_string (key
);
225 TRY_CATCH (except
, RETURN_MASK_ALL
)
227 struct value
*tmp
= self_value
->value
;
230 res_val
= value_struct_elt (&tmp
, NULL
, field
, 0, NULL
);
233 /* Assume we are attempting an array access, and let the
234 value code throw an exception if the index has an invalid
236 struct value
*idx
= convert_value_from_python (key
);
240 res_val
= value_subscript (tmp
, idx
);
245 GDB_PY_HANDLE_EXCEPTION (except
);
247 return value_to_value_object (res_val
);
251 valpy_setitem (PyObject
*self
, PyObject
*key
, PyObject
*value
)
253 PyErr_Format (PyExc_NotImplementedError
,
254 _("Setting of struct elements is not currently supported."));
258 /* Called by the Python interpreter to obtain string representation
261 valpy_str (PyObject
*self
)
266 struct cleanup
*old_chain
;
268 struct value_print_options opts
;
269 volatile struct gdb_exception except
;
271 get_user_print_options (&opts
);
274 stb
= mem_fileopen ();
275 old_chain
= make_cleanup_ui_file_delete (stb
);
277 TRY_CATCH (except
, RETURN_MASK_ALL
)
279 common_val_print (((value_object
*) self
)->value
, stb
, 0,
280 &opts
, current_language
);
281 s
= ui_file_xstrdup (stb
, &dummy
);
283 GDB_PY_HANDLE_EXCEPTION (except
);
285 do_cleanups (old_chain
);
287 result
= PyUnicode_Decode (s
, strlen (s
), host_charset (), NULL
);
293 /* Implements gdb.Value.is_optimized_out. */
295 valpy_get_is_optimized_out (PyObject
*self
, void *closure
)
297 struct value
*value
= ((value_object
*) self
)->value
;
299 if (value_optimized_out (value
))
320 /* If TYPE is a reference, return the target; otherwise return TYPE. */
321 #define STRIP_REFERENCE(TYPE) \
322 ((TYPE_CODE (TYPE) == TYPE_CODE_REF) ? (TYPE_TARGET_TYPE (TYPE)) : (TYPE))
324 /* Returns a value object which is the result of applying the operation
325 specified by OPCODE to the given arguments. */
327 valpy_binop (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
329 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
330 volatile struct gdb_exception except
;
332 TRY_CATCH (except
, RETURN_MASK_ALL
)
334 struct value
*arg1
, *arg2
;
336 /* If the gdb.Value object is the second operand, then it will be passed
337 to us as the OTHER argument, and SELF will be an entirely different
338 kind of object, altogether. Because of this, we can't assume self is
339 a gdb.Value object and need to convert it from python as well. */
340 arg1
= convert_value_from_python (self
);
344 arg2
= convert_value_from_python (other
);
352 struct type
*ltype
= value_type (arg1
);
353 struct type
*rtype
= value_type (arg2
);
355 CHECK_TYPEDEF (ltype
);
356 ltype
= STRIP_REFERENCE (ltype
);
357 CHECK_TYPEDEF (rtype
);
358 rtype
= STRIP_REFERENCE (rtype
);
360 if (TYPE_CODE (ltype
) == TYPE_CODE_PTR
)
361 res_val
= value_ptradd (arg1
, arg2
);
362 else if (TYPE_CODE (rtype
) == TYPE_CODE_PTR
)
363 res_val
= value_ptradd (arg2
, arg1
);
365 res_val
= value_binop (arg1
, arg2
, BINOP_ADD
);
370 struct type
*ltype
= value_type (arg1
);
371 struct type
*rtype
= value_type (arg2
);
373 CHECK_TYPEDEF (ltype
);
374 ltype
= STRIP_REFERENCE (ltype
);
375 CHECK_TYPEDEF (rtype
);
376 rtype
= STRIP_REFERENCE (rtype
);
378 if (TYPE_CODE (ltype
) == TYPE_CODE_PTR
)
380 if (TYPE_CODE (rtype
) == TYPE_CODE_PTR
)
381 /* A ptrdiff_t for the target would be preferable
383 res_val
= value_from_longest (builtin_type_pyint
,
384 value_ptrdiff (arg1
, arg2
));
386 res_val
= value_ptrsub (arg1
, arg2
);
389 res_val
= value_binop (arg1
, arg2
, BINOP_SUB
);
393 res_val
= value_binop (arg1
, arg2
, BINOP_MUL
);
396 res_val
= value_binop (arg1
, arg2
, BINOP_DIV
);
399 res_val
= value_binop (arg1
, arg2
, BINOP_REM
);
402 res_val
= value_binop (arg1
, arg2
, BINOP_EXP
);
405 res_val
= value_binop (arg1
, arg2
, BINOP_LSH
);
408 res_val
= value_binop (arg1
, arg2
, BINOP_RSH
);
411 res_val
= value_binop (arg1
, arg2
, BINOP_BITWISE_AND
);
414 res_val
= value_binop (arg1
, arg2
, BINOP_BITWISE_IOR
);
417 res_val
= value_binop (arg1
, arg2
, BINOP_BITWISE_XOR
);
421 GDB_PY_HANDLE_EXCEPTION (except
);
423 return res_val
? value_to_value_object (res_val
) : NULL
;
427 valpy_add (PyObject
*self
, PyObject
*other
)
429 return valpy_binop (VALPY_ADD
, self
, other
);
433 valpy_subtract (PyObject
*self
, PyObject
*other
)
435 return valpy_binop (VALPY_SUB
, self
, other
);
439 valpy_multiply (PyObject
*self
, PyObject
*other
)
441 return valpy_binop (VALPY_MUL
, self
, other
);
445 valpy_divide (PyObject
*self
, PyObject
*other
)
447 return valpy_binop (VALPY_DIV
, self
, other
);
451 valpy_remainder (PyObject
*self
, PyObject
*other
)
453 return valpy_binop (VALPY_REM
, self
, other
);
457 valpy_power (PyObject
*self
, PyObject
*other
, PyObject
*unused
)
459 /* We don't support the ternary form of pow. I don't know how to express
460 that, so let's just throw NotImplementedError to at least do something
462 if (unused
!= Py_None
)
464 PyErr_SetString (PyExc_NotImplementedError
,
465 "Invalid operation on gdb.Value.");
469 return valpy_binop (VALPY_POW
, self
, other
);
473 valpy_negative (PyObject
*self
)
475 struct value
*val
= NULL
;
476 volatile struct gdb_exception except
;
478 TRY_CATCH (except
, RETURN_MASK_ALL
)
480 val
= value_neg (((value_object
*) self
)->value
);
482 GDB_PY_HANDLE_EXCEPTION (except
);
484 return value_to_value_object (val
);
488 valpy_positive (PyObject
*self
)
490 struct value
*copy
= value_copy (((value_object
*) self
)->value
);
492 return value_to_value_object (copy
);
496 valpy_absolute (PyObject
*self
)
498 if (value_less (((value_object
*) self
)->value
,
499 value_from_longest (builtin_type_int8
, 0)))
500 return valpy_negative (self
);
502 return valpy_positive (self
);
505 /* Implements boolean evaluation of gdb.Value. */
507 valpy_nonzero (PyObject
*self
)
509 value_object
*self_value
= (value_object
*) self
;
512 type
= check_typedef (value_type (self_value
->value
));
514 if (is_integral_type (type
) || TYPE_CODE (type
) == TYPE_CODE_PTR
)
515 return !!value_as_long (self_value
->value
);
516 else if (TYPE_CODE (type
) == TYPE_CODE_FLT
)
517 return value_as_double (self_value
->value
) != 0;
518 else if (TYPE_CODE (type
) == TYPE_CODE_DECFLOAT
)
519 return !decimal_is_zero (value_contents (self_value
->value
),
523 PyErr_SetString (PyExc_TypeError
, _("Attempted truth testing on invalid "
529 /* Implements ~ for value objects. */
531 valpy_invert (PyObject
*self
)
533 struct value
*val
= NULL
;
534 volatile struct gdb_exception except
;
536 TRY_CATCH (except
, RETURN_MASK_ALL
)
538 val
= value_complement (((value_object
*) self
)->value
);
540 GDB_PY_HANDLE_EXCEPTION (except
);
542 return value_to_value_object (val
);
545 /* Implements left shift for value objects. */
547 valpy_lsh (PyObject
*self
, PyObject
*other
)
549 return valpy_binop (VALPY_LSH
, self
, other
);
552 /* Implements right shift for value objects. */
554 valpy_rsh (PyObject
*self
, PyObject
*other
)
556 return valpy_binop (VALPY_RSH
, self
, other
);
559 /* Implements bitwise and for value objects. */
561 valpy_and (PyObject
*self
, PyObject
*other
)
563 return valpy_binop (VALPY_BITAND
, self
, other
);
566 /* Implements bitwise or for value objects. */
568 valpy_or (PyObject
*self
, PyObject
*other
)
570 return valpy_binop (VALPY_BITOR
, self
, other
);
573 /* Implements bitwise xor for value objects. */
575 valpy_xor (PyObject
*self
, PyObject
*other
)
577 return valpy_binop (VALPY_BITXOR
, self
, other
);
580 /* Implements comparison operations for value objects. */
582 valpy_richcompare (PyObject
*self
, PyObject
*other
, int op
)
585 struct value
*value_other
;
586 volatile struct gdb_exception except
;
588 if (other
== Py_None
)
589 /* Comparing with None is special. From what I can tell, in Python
590 None is smaller than anything else. */
602 PyErr_SetString (PyExc_NotImplementedError
,
603 "Invalid operation on gdb.Value.");
607 TRY_CATCH (except
, RETURN_MASK_ALL
)
609 value_other
= convert_value_from_python (other
);
610 if (value_other
== NULL
)
615 result
= value_less (((value_object
*) self
)->value
, value_other
);
618 result
= value_less (((value_object
*) self
)->value
, value_other
)
619 || value_equal (((value_object
*) self
)->value
, value_other
);
622 result
= value_equal (((value_object
*) self
)->value
, value_other
);
625 result
= !value_equal (((value_object
*) self
)->value
, value_other
);
628 result
= value_less (value_other
, ((value_object
*) self
)->value
);
631 result
= value_less (value_other
, ((value_object
*) self
)->value
)
632 || value_equal (((value_object
*) self
)->value
, value_other
);
636 PyErr_SetString (PyExc_NotImplementedError
,
637 "Invalid operation on gdb.Value.");
641 GDB_PY_HANDLE_EXCEPTION (except
);
649 /* Helper function to determine if a type is "int-like". */
651 is_intlike (struct type
*type
, int ptr_ok
)
653 CHECK_TYPEDEF (type
);
654 return (TYPE_CODE (type
) == TYPE_CODE_INT
655 || TYPE_CODE (type
) == TYPE_CODE_ENUM
656 || TYPE_CODE (type
) == TYPE_CODE_BOOL
657 || TYPE_CODE (type
) == TYPE_CODE_CHAR
658 || (ptr_ok
&& TYPE_CODE (type
) == TYPE_CODE_PTR
));
661 /* Implements conversion to int. */
663 valpy_int (PyObject
*self
)
665 struct value
*value
= ((value_object
*) self
)->value
;
666 struct type
*type
= value_type (value
);
668 volatile struct gdb_exception except
;
670 CHECK_TYPEDEF (type
);
671 if (!is_intlike (type
, 0))
673 PyErr_SetString (PyExc_RuntimeError
, "cannot convert value to int");
677 TRY_CATCH (except
, RETURN_MASK_ALL
)
679 l
= value_as_long (value
);
681 GDB_PY_HANDLE_EXCEPTION (except
);
683 return PyInt_FromLong (l
);
686 /* Implements conversion to long. */
688 valpy_long (PyObject
*self
)
690 struct value
*value
= ((value_object
*) self
)->value
;
691 struct type
*type
= value_type (value
);
693 volatile struct gdb_exception except
;
695 if (!is_intlike (type
, 1))
697 PyErr_SetString (PyExc_RuntimeError
, "cannot convert value to long");
701 TRY_CATCH (except
, RETURN_MASK_ALL
)
703 l
= value_as_long (value
);
705 GDB_PY_HANDLE_EXCEPTION (except
);
707 return PyLong_FromLong (l
);
710 /* Implements conversion to float. */
712 valpy_float (PyObject
*self
)
714 struct value
*value
= ((value_object
*) self
)->value
;
715 struct type
*type
= value_type (value
);
717 volatile struct gdb_exception except
;
719 CHECK_TYPEDEF (type
);
720 if (TYPE_CODE (type
) != TYPE_CODE_FLT
)
722 PyErr_SetString (PyExc_RuntimeError
, "cannot convert value to float");
726 TRY_CATCH (except
, RETURN_MASK_ALL
)
728 d
= value_as_double (value
);
730 GDB_PY_HANDLE_EXCEPTION (except
);
732 return PyFloat_FromDouble (d
);
735 /* Returns an object for a value which is released from the all_values chain,
736 so its lifetime is not bound to the execution of a command. */
738 value_to_value_object (struct value
*val
)
740 value_object
*val_obj
;
742 val_obj
= PyObject_New (value_object
, &value_object_type
);
745 val_obj
->value
= val
;
746 val_obj
->address
= NULL
;
748 value_prepend_to_list (&values_in_python
, val
);
751 return (PyObject
*) val_obj
;
754 /* Try to convert a Python value to a gdb value. If the value cannot
755 be converted, set a Python exception and return NULL. */
758 convert_value_from_python (PyObject
*obj
)
760 struct value
*value
= NULL
; /* -Wall */
761 PyObject
*target_str
, *unicode_str
;
763 volatile struct gdb_exception except
;
766 gdb_assert (obj
!= NULL
);
768 TRY_CATCH (except
, RETURN_MASK_ALL
)
770 if (PyBool_Check (obj
))
772 cmp
= PyObject_IsTrue (obj
);
774 value
= value_from_longest (builtin_type_pybool
, cmp
);
776 else if (PyInt_Check (obj
))
778 long l
= PyInt_AsLong (obj
);
780 if (! PyErr_Occurred ())
781 value
= value_from_longest (builtin_type_pyint
, l
);
783 else if (PyLong_Check (obj
))
785 LONGEST l
= PyLong_AsLongLong (obj
);
787 if (! PyErr_Occurred ())
788 value
= value_from_longest (builtin_type_pylong
, l
);
790 else if (PyFloat_Check (obj
))
792 double d
= PyFloat_AsDouble (obj
);
794 if (! PyErr_Occurred ())
795 value
= value_from_double (builtin_type_pyfloat
, d
);
797 else if (gdbpy_is_string (obj
))
801 s
= python_string_to_target_string (obj
);
804 old
= make_cleanup (xfree
, s
);
805 value
= value_from_string (s
);
809 else if (PyObject_TypeCheck (obj
, &value_object_type
))
810 value
= value_copy (((value_object
*) obj
)->value
);
812 PyErr_Format (PyExc_TypeError
, _("Could not convert Python object: %s"),
813 PyString_AsString (PyObject_Str (obj
)));
815 if (except
.reason
< 0)
817 PyErr_Format (except
.reason
== RETURN_QUIT
818 ? PyExc_KeyboardInterrupt
: PyExc_RuntimeError
,
819 "%s", except
.message
);
826 /* Returns value object in the ARGth position in GDB's history. */
828 gdbpy_history (PyObject
*self
, PyObject
*args
)
831 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
832 volatile struct gdb_exception except
;
834 if (!PyArg_ParseTuple (args
, "i", &i
))
837 TRY_CATCH (except
, RETURN_MASK_ALL
)
839 res_val
= access_value_history (i
);
841 GDB_PY_HANDLE_EXCEPTION (except
);
843 return value_to_value_object (res_val
);
847 gdbpy_initialize_values (void)
849 if (PyType_Ready (&value_object_type
) < 0)
852 Py_INCREF (&value_object_type
);
853 PyModule_AddObject (gdb_module
, "Value", (PyObject
*) &value_object_type
);
855 values_in_python
= NULL
;
858 static PyGetSetDef value_object_getset
[] = {
859 { "address", valpy_get_address
, NULL
, "The address of the value.",
861 { "is_optimized_out", valpy_get_is_optimized_out
, NULL
,
862 "Boolean telling whether the value is optimized out (i.e., not available).",
864 {NULL
} /* Sentinel */
867 static PyMethodDef value_object_methods
[] = {
868 { "dereference", valpy_dereference
, METH_NOARGS
, "Dereferences the value." },
869 { "string", (PyCFunction
) valpy_string
, METH_VARARGS
| METH_KEYWORDS
,
870 "string ([encoding] [, errors]) -> string\n\
871 Return Unicode string representation of the value." },
872 {NULL
} /* Sentinel */
875 static PyNumberMethods value_object_as_number
= {
881 NULL
, /* nb_divmod */
882 valpy_power
, /* nb_power */
883 valpy_negative
, /* nb_negative */
884 valpy_positive
, /* nb_positive */
885 valpy_absolute
, /* nb_absolute */
886 valpy_nonzero
, /* nb_nonzero */
887 valpy_invert
, /* nb_invert */
888 valpy_lsh
, /* nb_lshift */
889 valpy_rsh
, /* nb_rshift */
890 valpy_and
, /* nb_and */
891 valpy_xor
, /* nb_xor */
892 valpy_or
, /* nb_or */
893 NULL
, /* nb_coerce */
894 valpy_int
, /* nb_int */
895 valpy_long
, /* nb_long */
896 valpy_float
, /* nb_float */
901 static PyMappingMethods value_object_as_mapping
= {
907 PyTypeObject value_object_type
= {
908 PyObject_HEAD_INIT (NULL
)
910 "gdb.Value", /*tp_name*/
911 sizeof (value_object
), /*tp_basicsize*/
913 valpy_dealloc
, /*tp_dealloc*/
919 &value_object_as_number
, /*tp_as_number*/
920 0, /*tp_as_sequence*/
921 &value_object_as_mapping
, /*tp_as_mapping*/
924 valpy_str
, /*tp_str*/
928 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
, /*tp_flags*/
929 "GDB value object", /* tp_doc */
932 valpy_richcompare
, /* tp_richcompare */
933 0, /* tp_weaklistoffset */
936 value_object_methods
, /* tp_methods */
938 value_object_getset
, /* tp_getset */
941 0, /* tp_descr_get */
942 0, /* tp_descr_set */
943 0, /* tp_dictoffset */
946 valpy_new
/* tp_new */
949 #endif /* HAVE_PYTHON */