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 if (!self
->owned_by_gdb
)
73 value_free (self
->value
);
74 self
->ob_type
->tp_free (self
);
77 /* Called when a new gdb.Value object needs to be allocated. */
79 valpy_new (PyTypeObject
*subtype
, PyObject
*args
, PyObject
*keywords
)
81 struct value
*value
= NULL
; /* Initialize to appease gcc warning. */
82 value_object
*value_obj
;
84 if (PyTuple_Size (args
) != 1)
86 PyErr_SetString (PyExc_TypeError
, _("Value object creation takes only "
91 value_obj
= (value_object
*) subtype
->tp_alloc (subtype
, 1);
92 if (value_obj
== NULL
)
94 PyErr_SetString (PyExc_MemoryError
, _("Could not allocate memory to "
95 "create Value object."));
99 value
= convert_value_from_python (PyTuple_GetItem (args
, 0));
102 subtype
->tp_free (value_obj
);
106 value_obj
->value
= value
;
107 value_obj
->owned_by_gdb
= 0;
108 release_value (value
);
109 value_prepend_to_list (&values_in_python
, value
);
111 return (PyObject
*) value_obj
;
114 /* Given a value of a pointer type, apply the C unary * operator to it. */
116 valpy_dereference (PyObject
*self
, PyObject
*args
)
118 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
119 volatile struct gdb_exception except
;
121 TRY_CATCH (except
, RETURN_MASK_ALL
)
123 res_val
= value_ind (((value_object
*) self
)->value
);
125 GDB_PY_HANDLE_EXCEPTION (except
);
127 return value_to_value_object (res_val
);
130 /* Return "&value". */
132 valpy_address (PyObject
*self
, PyObject
*args
)
134 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
135 volatile struct gdb_exception except
;
137 TRY_CATCH (except
, RETURN_MASK_ALL
)
139 res_val
= value_addr (((value_object
*) self
)->value
);
141 GDB_PY_HANDLE_EXCEPTION (except
);
143 return value_to_value_object (res_val
);
146 /* Implementation of gdb.Value.string ([encoding] [, errors]) -> string
147 Return Unicode string with value contents. If ENCODING is not given,
148 the string is assumed to be encoded in the target's charset. */
150 valpy_string (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
154 struct value
*value
= ((value_object
*) self
)->value
;
155 volatile struct gdb_exception except
;
157 const char *encoding
= NULL
;
158 const char *errors
= NULL
;
159 const char *user_encoding
= NULL
;
160 const char *la_encoding
= NULL
;
161 static char *keywords
[] = { "encoding", "errors" };
163 if (!PyArg_ParseTupleAndKeywords (args
, kw
, "|ss", keywords
,
164 &user_encoding
, &errors
))
167 TRY_CATCH (except
, RETURN_MASK_ALL
)
169 LA_GET_STRING (value
, &buffer
, &length
, &la_encoding
);
171 GDB_PY_HANDLE_EXCEPTION (except
);
173 encoding
= (user_encoding
&& *user_encoding
) ? user_encoding
: la_encoding
;
174 unicode
= PyUnicode_Decode (buffer
, length
, encoding
, errors
);
181 valpy_length (PyObject
*self
)
183 /* We don't support getting the number of elements in a struct / class. */
184 PyErr_SetString (PyExc_NotImplementedError
,
185 "Invalid operation on gdb.Value.");
189 /* Given string name of an element inside structure, return its value
192 valpy_getitem (PyObject
*self
, PyObject
*key
)
194 value_object
*self_value
= (value_object
*) self
;
196 struct value
*idx
= NULL
;
197 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
198 volatile struct gdb_exception except
;
200 if (gdbpy_is_string (key
))
202 field
= python_string_to_host_string (key
);
207 TRY_CATCH (except
, RETURN_MASK_ALL
)
209 struct value
*tmp
= self_value
->value
;
212 res_val
= value_struct_elt (&tmp
, NULL
, field
, 0, NULL
);
215 /* Assume we are attempting an array access, and let the
216 value code throw an exception if the index has an invalid
218 struct value
*idx
= convert_value_from_python (key
);
222 res_val
= value_subscript (tmp
, idx
);
227 GDB_PY_HANDLE_EXCEPTION (except
);
229 return value_to_value_object (res_val
);
233 valpy_setitem (PyObject
*self
, PyObject
*key
, PyObject
*value
)
235 PyErr_Format (PyExc_NotImplementedError
,
236 _("Setting of struct elements is not currently supported."));
240 /* Called by the Python interpreter to obtain string representation
243 valpy_str (PyObject
*self
)
248 struct cleanup
*old_chain
;
250 struct value_print_options opts
;
251 volatile struct gdb_exception except
;
253 get_user_print_options (&opts
);
256 stb
= mem_fileopen ();
257 old_chain
= make_cleanup_ui_file_delete (stb
);
259 TRY_CATCH (except
, RETURN_MASK_ALL
)
261 common_val_print (((value_object
*) self
)->value
, stb
, 0,
262 &opts
, current_language
);
263 s
= ui_file_xstrdup (stb
, &dummy
);
265 GDB_PY_HANDLE_EXCEPTION (except
);
267 do_cleanups (old_chain
);
269 result
= PyUnicode_Decode (s
, strlen (s
), host_charset (), NULL
);
290 /* If TYPE is a reference, return the target; otherwise return TYPE. */
291 #define STRIP_REFERENCE(TYPE) \
292 ((TYPE_CODE (TYPE) == TYPE_CODE_REF) ? (TYPE_TARGET_TYPE (TYPE)) : (TYPE))
294 /* Returns a value object which is the result of applying the operation
295 specified by OPCODE to the given arguments. */
297 valpy_binop (enum valpy_opcode opcode
, PyObject
*self
, PyObject
*other
)
299 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
300 volatile struct gdb_exception except
;
302 TRY_CATCH (except
, RETURN_MASK_ALL
)
304 struct value
*arg1
, *arg2
;
306 /* If the gdb.Value object is the second operand, then it will be passed
307 to us as the OTHER argument, and SELF will be an entirely different
308 kind of object, altogether. Because of this, we can't assume self is
309 a gdb.Value object and need to convert it from python as well. */
310 arg1
= convert_value_from_python (self
);
314 arg2
= convert_value_from_python (other
);
322 struct type
*ltype
= value_type (arg1
);
323 struct type
*rtype
= value_type (arg2
);
325 CHECK_TYPEDEF (ltype
);
326 ltype
= STRIP_REFERENCE (ltype
);
327 CHECK_TYPEDEF (rtype
);
328 rtype
= STRIP_REFERENCE (rtype
);
330 if (TYPE_CODE (ltype
) == TYPE_CODE_PTR
)
331 res_val
= value_ptradd (arg1
, arg2
);
332 else if (TYPE_CODE (rtype
) == TYPE_CODE_PTR
)
333 res_val
= value_ptradd (arg2
, arg1
);
335 res_val
= value_binop (arg1
, arg2
, BINOP_ADD
);
340 struct type
*ltype
= value_type (arg1
);
341 struct type
*rtype
= value_type (arg2
);
343 CHECK_TYPEDEF (ltype
);
344 ltype
= STRIP_REFERENCE (ltype
);
345 CHECK_TYPEDEF (rtype
);
346 rtype
= STRIP_REFERENCE (rtype
);
348 if (TYPE_CODE (ltype
) == TYPE_CODE_PTR
)
350 if (TYPE_CODE (rtype
) == TYPE_CODE_PTR
)
351 /* A ptrdiff_t for the target would be preferable
353 res_val
= value_from_longest (builtin_type_pyint
,
354 value_ptrdiff (arg1
, arg2
));
356 res_val
= value_ptrsub (arg1
, arg2
);
359 res_val
= value_binop (arg1
, arg2
, BINOP_SUB
);
363 res_val
= value_binop (arg1
, arg2
, BINOP_MUL
);
366 res_val
= value_binop (arg1
, arg2
, BINOP_DIV
);
369 res_val
= value_binop (arg1
, arg2
, BINOP_REM
);
372 res_val
= value_binop (arg1
, arg2
, BINOP_EXP
);
375 res_val
= value_binop (arg1
, arg2
, BINOP_LSH
);
378 res_val
= value_binop (arg1
, arg2
, BINOP_RSH
);
381 res_val
= value_binop (arg1
, arg2
, BINOP_BITWISE_AND
);
384 res_val
= value_binop (arg1
, arg2
, BINOP_BITWISE_IOR
);
387 res_val
= value_binop (arg1
, arg2
, BINOP_BITWISE_XOR
);
391 GDB_PY_HANDLE_EXCEPTION (except
);
393 return res_val
? value_to_value_object (res_val
) : NULL
;
397 valpy_add (PyObject
*self
, PyObject
*other
)
399 return valpy_binop (VALPY_ADD
, self
, other
);
403 valpy_subtract (PyObject
*self
, PyObject
*other
)
405 return valpy_binop (VALPY_SUB
, self
, other
);
409 valpy_multiply (PyObject
*self
, PyObject
*other
)
411 return valpy_binop (VALPY_MUL
, self
, other
);
415 valpy_divide (PyObject
*self
, PyObject
*other
)
417 return valpy_binop (VALPY_DIV
, self
, other
);
421 valpy_remainder (PyObject
*self
, PyObject
*other
)
423 return valpy_binop (VALPY_REM
, self
, other
);
427 valpy_power (PyObject
*self
, PyObject
*other
, PyObject
*unused
)
429 /* We don't support the ternary form of pow. I don't know how to express
430 that, so let's just throw NotImplementedError to at least do something
432 if (unused
!= Py_None
)
434 PyErr_SetString (PyExc_NotImplementedError
,
435 "Invalid operation on gdb.Value.");
439 return valpy_binop (VALPY_POW
, self
, other
);
443 valpy_negative (PyObject
*self
)
445 struct value
*val
= NULL
;
446 volatile struct gdb_exception except
;
448 TRY_CATCH (except
, RETURN_MASK_ALL
)
450 val
= value_neg (((value_object
*) self
)->value
);
452 GDB_PY_HANDLE_EXCEPTION (except
);
454 return value_to_value_object (val
);
458 valpy_positive (PyObject
*self
)
460 struct value
*copy
= value_copy (((value_object
*) self
)->value
);
462 return value_to_value_object (copy
);
466 valpy_absolute (PyObject
*self
)
468 if (value_less (((value_object
*) self
)->value
,
469 value_from_longest (builtin_type_int8
, 0)))
470 return valpy_negative (self
);
472 return valpy_positive (self
);
475 /* Implements boolean evaluation of gdb.Value. */
477 valpy_nonzero (PyObject
*self
)
479 value_object
*self_value
= (value_object
*) self
;
482 type
= check_typedef (value_type (self_value
->value
));
484 if (is_integral_type (type
) || TYPE_CODE (type
) == TYPE_CODE_PTR
)
485 return !!value_as_long (self_value
->value
);
486 else if (TYPE_CODE (type
) == TYPE_CODE_FLT
)
487 return value_as_double (self_value
->value
) != 0;
488 else if (TYPE_CODE (type
) == TYPE_CODE_DECFLOAT
)
489 return !decimal_is_zero (value_contents (self_value
->value
),
493 PyErr_SetString (PyExc_TypeError
, _("Attempted truth testing on invalid "
499 /* Implements ~ for value objects. */
501 valpy_invert (PyObject
*self
)
503 struct value
*val
= NULL
;
504 volatile struct gdb_exception except
;
506 TRY_CATCH (except
, RETURN_MASK_ALL
)
508 val
= value_complement (((value_object
*) self
)->value
);
510 GDB_PY_HANDLE_EXCEPTION (except
);
512 return value_to_value_object (val
);
515 /* Implements left shift for value objects. */
517 valpy_lsh (PyObject
*self
, PyObject
*other
)
519 return valpy_binop (VALPY_LSH
, self
, other
);
522 /* Implements right shift for value objects. */
524 valpy_rsh (PyObject
*self
, PyObject
*other
)
526 return valpy_binop (VALPY_RSH
, self
, other
);
529 /* Implements bitwise and for value objects. */
531 valpy_and (PyObject
*self
, PyObject
*other
)
533 return valpy_binop (VALPY_BITAND
, self
, other
);
536 /* Implements bitwise or for value objects. */
538 valpy_or (PyObject
*self
, PyObject
*other
)
540 return valpy_binop (VALPY_BITOR
, self
, other
);
543 /* Implements bitwise xor for value objects. */
545 valpy_xor (PyObject
*self
, PyObject
*other
)
547 return valpy_binop (VALPY_BITXOR
, self
, other
);
550 /* Implements comparison operations for value objects. */
552 valpy_richcompare (PyObject
*self
, PyObject
*other
, int op
)
555 struct value
*value_other
;
556 volatile struct gdb_exception except
;
558 if (other
== Py_None
)
559 /* Comparing with None is special. From what I can tell, in Python
560 None is smaller than anything else. */
572 PyErr_SetString (PyExc_NotImplementedError
,
573 "Invalid operation on gdb.Value.");
577 TRY_CATCH (except
, RETURN_MASK_ALL
)
579 value_other
= convert_value_from_python (other
);
580 if (value_other
== NULL
)
585 result
= value_less (((value_object
*) self
)->value
, value_other
);
588 result
= value_less (((value_object
*) self
)->value
, value_other
)
589 || value_equal (((value_object
*) self
)->value
, value_other
);
592 result
= value_equal (((value_object
*) self
)->value
, value_other
);
595 result
= !value_equal (((value_object
*) self
)->value
, value_other
);
598 result
= value_less (value_other
, ((value_object
*) self
)->value
);
601 result
= value_less (value_other
, ((value_object
*) self
)->value
)
602 || value_equal (((value_object
*) self
)->value
, value_other
);
606 PyErr_SetString (PyExc_NotImplementedError
,
607 "Invalid operation on gdb.Value.");
611 GDB_PY_HANDLE_EXCEPTION (except
);
619 /* Helper function to determine if a type is "int-like". */
621 is_intlike (struct type
*type
, int ptr_ok
)
623 CHECK_TYPEDEF (type
);
624 return (TYPE_CODE (type
) == TYPE_CODE_INT
625 || TYPE_CODE (type
) == TYPE_CODE_ENUM
626 || TYPE_CODE (type
) == TYPE_CODE_BOOL
627 || TYPE_CODE (type
) == TYPE_CODE_CHAR
628 || (ptr_ok
&& TYPE_CODE (type
) == TYPE_CODE_PTR
));
631 /* Implements conversion to int. */
633 valpy_int (PyObject
*self
)
635 struct value
*value
= ((value_object
*) self
)->value
;
636 struct type
*type
= value_type (value
);
638 volatile struct gdb_exception except
;
640 CHECK_TYPEDEF (type
);
641 if (!is_intlike (type
, 0))
643 PyErr_SetString (PyExc_RuntimeError
, "cannot convert value to int");
647 TRY_CATCH (except
, RETURN_MASK_ALL
)
649 l
= value_as_long (value
);
651 GDB_PY_HANDLE_EXCEPTION (except
);
653 return PyInt_FromLong (l
);
656 /* Implements conversion to long. */
658 valpy_long (PyObject
*self
)
660 struct value
*value
= ((value_object
*) self
)->value
;
661 struct type
*type
= value_type (value
);
663 volatile struct gdb_exception except
;
665 if (!is_intlike (type
, 1))
667 PyErr_SetString (PyExc_RuntimeError
, "cannot convert value to long");
671 TRY_CATCH (except
, RETURN_MASK_ALL
)
673 l
= value_as_long (value
);
675 GDB_PY_HANDLE_EXCEPTION (except
);
677 return PyLong_FromLong (l
);
680 /* Implements conversion to float. */
682 valpy_float (PyObject
*self
)
684 struct value
*value
= ((value_object
*) self
)->value
;
685 struct type
*type
= value_type (value
);
687 volatile struct gdb_exception except
;
689 CHECK_TYPEDEF (type
);
690 if (TYPE_CODE (type
) != TYPE_CODE_FLT
)
692 PyErr_SetString (PyExc_RuntimeError
, "cannot convert value to float");
696 TRY_CATCH (except
, RETURN_MASK_ALL
)
698 d
= value_as_double (value
);
700 GDB_PY_HANDLE_EXCEPTION (except
);
702 return PyFloat_FromDouble (d
);
705 /* Returns an object for a value which is released from the all_values chain,
706 so its lifetime is not bound to the execution of a command. */
708 value_to_value_object (struct value
*val
)
710 value_object
*val_obj
;
712 val_obj
= PyObject_New (value_object
, &value_object_type
);
715 val_obj
->value
= val
;
716 val_obj
->owned_by_gdb
= 0;
718 value_prepend_to_list (&values_in_python
, val
);
721 return (PyObject
*) val_obj
;
724 /* Try to convert a Python value to a gdb value. If the value cannot
725 be converted, set a Python exception and return NULL. */
728 convert_value_from_python (PyObject
*obj
)
730 struct value
*value
= NULL
; /* -Wall */
731 PyObject
*target_str
, *unicode_str
;
733 volatile struct gdb_exception except
;
736 gdb_assert (obj
!= NULL
);
738 TRY_CATCH (except
, RETURN_MASK_ALL
)
740 if (PyBool_Check (obj
))
742 cmp
= PyObject_IsTrue (obj
);
744 value
= value_from_longest (builtin_type_pybool
, cmp
);
746 else if (PyInt_Check (obj
))
748 long l
= PyInt_AsLong (obj
);
750 if (! PyErr_Occurred ())
751 value
= value_from_longest (builtin_type_pyint
, l
);
753 else if (PyLong_Check (obj
))
755 LONGEST l
= PyLong_AsLongLong (obj
);
757 if (! PyErr_Occurred ())
758 value
= value_from_longest (builtin_type_pylong
, l
);
760 else if (PyFloat_Check (obj
))
762 double d
= PyFloat_AsDouble (obj
);
764 if (! PyErr_Occurred ())
765 value
= value_from_double (builtin_type_pyfloat
, d
);
767 else if (gdbpy_is_string (obj
))
771 s
= python_string_to_target_string (obj
);
774 old
= make_cleanup (xfree
, s
);
775 value
= value_from_string (s
);
779 else if (PyObject_TypeCheck (obj
, &value_object_type
))
780 value
= value_copy (((value_object
*) obj
)->value
);
782 PyErr_Format (PyExc_TypeError
, _("Could not convert Python object: %s"),
783 PyString_AsString (PyObject_Str (obj
)));
785 if (except
.reason
< 0)
787 PyErr_Format (except
.reason
== RETURN_QUIT
788 ? PyExc_KeyboardInterrupt
: PyExc_RuntimeError
,
789 "%s", except
.message
);
796 /* Returns value object in the ARGth position in GDB's history. */
798 gdbpy_history (PyObject
*self
, PyObject
*args
)
801 struct value
*res_val
= NULL
; /* Initialize to appease gcc warning. */
802 volatile struct gdb_exception except
;
804 if (!PyArg_ParseTuple (args
, "i", &i
))
807 TRY_CATCH (except
, RETURN_MASK_ALL
)
809 res_val
= access_value_history (i
);
811 GDB_PY_HANDLE_EXCEPTION (except
);
813 return value_to_value_object (res_val
);
817 gdbpy_initialize_values (void)
819 if (PyType_Ready (&value_object_type
) < 0)
822 Py_INCREF (&value_object_type
);
823 PyModule_AddObject (gdb_module
, "Value", (PyObject
*) &value_object_type
);
825 values_in_python
= NULL
;
828 static PyMethodDef value_object_methods
[] = {
829 { "address", valpy_address
, METH_NOARGS
, "Return the address of the value." },
830 { "dereference", valpy_dereference
, METH_NOARGS
, "Dereferences the value." },
831 { "string", (PyCFunction
) valpy_string
, METH_VARARGS
| METH_KEYWORDS
,
832 "string ([encoding] [, errors]) -> string\n\
833 Return Unicode string representation of the value." },
834 {NULL
} /* Sentinel */
837 static PyNumberMethods value_object_as_number
= {
843 NULL
, /* nb_divmod */
844 valpy_power
, /* nb_power */
845 valpy_negative
, /* nb_negative */
846 valpy_positive
, /* nb_positive */
847 valpy_absolute
, /* nb_absolute */
848 valpy_nonzero
, /* nb_nonzero */
849 valpy_invert
, /* nb_invert */
850 valpy_lsh
, /* nb_lshift */
851 valpy_rsh
, /* nb_rshift */
852 valpy_and
, /* nb_and */
853 valpy_xor
, /* nb_xor */
854 valpy_or
, /* nb_or */
855 NULL
, /* nb_coerce */
856 valpy_int
, /* nb_int */
857 valpy_long
, /* nb_long */
858 valpy_float
, /* nb_float */
863 static PyMappingMethods value_object_as_mapping
= {
869 PyTypeObject value_object_type
= {
870 PyObject_HEAD_INIT (NULL
)
872 "gdb.Value", /*tp_name*/
873 sizeof (value_object
), /*tp_basicsize*/
875 valpy_dealloc
, /*tp_dealloc*/
881 &value_object_as_number
, /*tp_as_number*/
882 0, /*tp_as_sequence*/
883 &value_object_as_mapping
, /*tp_as_mapping*/
886 valpy_str
, /*tp_str*/
890 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
, /*tp_flags*/
891 "GDB value object", /* tp_doc */
894 valpy_richcompare
, /* tp_richcompare */
895 0, /* tp_weaklistoffset */
898 value_object_methods
, /* tp_methods */
903 0, /* tp_descr_get */
904 0, /* tp_descr_set */
905 0, /* tp_dictoffset */
908 valpy_new
/* tp_new */
911 #endif /* HAVE_PYTHON */