gdb/python/py-value.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Python interface to values.

  2.    Copyright (C) 2008-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "charset.h"
  16. #include "value.h"
  17. #include "language.h"
  18. #include "dfp.h"
  19. #include "valprint.h"
  20. #include "infcall.h"
  21. #include "expression.h"
  22. #include "cp-abi.h"
  23. #include "python.h"

  24. #include "python-internal.h"

  25. /* Even though Python scalar types directly map to host types, we use
  26.    target types here to remain consistent with the values system in
  27.    GDB (which uses target arithmetic).  */

  28. /* Python's integer type corresponds to C's long type.  */
  29. #define builtin_type_pyint builtin_type (python_gdbarch)->builtin_long

  30. /* Python's float type corresponds to C's double type.  */
  31. #define builtin_type_pyfloat builtin_type (python_gdbarch)->builtin_double

  32. /* Python's long type corresponds to C's long long type.  */
  33. #define builtin_type_pylong builtin_type (python_gdbarch)->builtin_long_long

  34. /* Python's long type corresponds to C's long long type.  Unsigned version.  */
  35. #define builtin_type_upylong builtin_type \
  36.   (python_gdbarch)->builtin_unsigned_long_long

  37. #define builtin_type_pybool \
  38.   language_bool_type (python_language, python_gdbarch)

  39. #define builtin_type_pychar \
  40.   language_string_char_type (python_language, python_gdbarch)

  41. typedef struct value_object {
  42.   PyObject_HEAD
  43.   struct value_object *next;
  44.   struct value_object *prev;
  45.   struct value *value;
  46.   PyObject *address;
  47.   PyObject *type;
  48.   PyObject *dynamic_type;
  49. } value_object;

  50. /* List of all values which are currently exposed to Python. It is
  51.    maintained so that when an objfile is discarded, preserve_values
  52.    can copy the values' types if needed.  */
  53. /* This variable is unnecessarily initialized to NULL in order to
  54.    work around a linker bug on MacOS.  */
  55. static value_object *values_in_python = NULL;

  56. /* Called by the Python interpreter when deallocating a value object.  */
  57. static void
  58. valpy_dealloc (PyObject *obj)
  59. {
  60.   value_object *self = (value_object *) obj;

  61.   /* Remove SELF from the global list.  */
  62.   if (self->prev)
  63.     self->prev->next = self->next;
  64.   else
  65.     {
  66.       gdb_assert (values_in_python == self);
  67.       values_in_python = self->next;
  68.     }
  69.   if (self->next)
  70.     self->next->prev = self->prev;

  71.   value_free (self->value);

  72.   if (self->address)
  73.     /* Use braces to appease gcc warning.  *sigh*  */
  74.     {
  75.       Py_DECREF (self->address);
  76.     }

  77.   if (self->type)
  78.     {
  79.       Py_DECREF (self->type);
  80.     }

  81.   Py_XDECREF (self->dynamic_type);

  82.   Py_TYPE (self)->tp_free (self);
  83. }

  84. /* Helper to push a Value object on the global list.  */
  85. static void
  86. note_value (value_object *value_obj)
  87. {
  88.   value_obj->next = values_in_python;
  89.   if (value_obj->next)
  90.     value_obj->next->prev = value_obj;
  91.   value_obj->prev = NULL;
  92.   values_in_python = value_obj;
  93. }

  94. /* Called when a new gdb.Value object needs to be allocated.  Returns NULL on
  95.    error, with a python exception set.  */
  96. static PyObject *
  97. valpy_new (PyTypeObject *subtype, PyObject *args, PyObject *keywords)
  98. {
  99.   struct value *value = NULL;   /* Initialize to appease gcc warning.  */
  100.   value_object *value_obj;

  101.   if (PyTuple_Size (args) != 1)
  102.     {
  103.       PyErr_SetString (PyExc_TypeError, _("Value object creation takes only "
  104.                                           "1 argument"));
  105.       return NULL;
  106.     }

  107.   value_obj = (value_object *) subtype->tp_alloc (subtype, 1);
  108.   if (value_obj == NULL)
  109.     {
  110.       PyErr_SetString (PyExc_MemoryError, _("Could not allocate memory to "
  111.                                             "create Value object."));
  112.       return NULL;
  113.     }

  114.   value = convert_value_from_python (PyTuple_GetItem (args, 0));
  115.   if (value == NULL)
  116.     {
  117.       subtype->tp_free (value_obj);
  118.       return NULL;
  119.     }

  120.   value_obj->value = value;
  121.   release_value_or_incref (value);
  122.   value_obj->address = NULL;
  123.   value_obj->type = NULL;
  124.   value_obj->dynamic_type = NULL;
  125.   note_value (value_obj);

  126.   return (PyObject *) value_obj;
  127. }

  128. /* Iterate over all the Value objects, calling preserve_one_value on
  129.    each.  */
  130. void
  131. gdbpy_preserve_values (const struct extension_language_defn *extlang,
  132.                        struct objfile *objfile, htab_t copied_types)
  133. {
  134.   value_object *iter;

  135.   for (iter = values_in_python; iter; iter = iter->next)
  136.     preserve_one_value (iter->value, objfile, copied_types);
  137. }

  138. /* Given a value of a pointer type, apply the C unary * operator to it.  */
  139. static PyObject *
  140. valpy_dereference (PyObject *self, PyObject *args)
  141. {
  142.   volatile struct gdb_exception except;
  143.   PyObject *result = NULL;

  144.   TRY_CATCH (except, RETURN_MASK_ALL)
  145.     {
  146.       struct value *res_val;
  147.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());

  148.       res_val = value_ind (((value_object *) self)->value);
  149.       result = value_to_value_object (res_val);
  150.       do_cleanups (cleanup);
  151.     }
  152.   GDB_PY_HANDLE_EXCEPTION (except);

  153.   return result;
  154. }

  155. /* Given a value of a pointer type or a reference type, return the value
  156.    referenced. The difference between this function and valpy_dereference is
  157.    that the latter applies * unary operator to a value, which need not always
  158.    result in the value referenced. For example, for a value which is a reference
  159.    to an 'int' pointer ('int *'), valpy_dereference will result in a value of
  160.    type 'int' while valpy_referenced_value will result in a value of type
  161.    'int *'.  */

  162. static PyObject *
  163. valpy_referenced_value (PyObject *self, PyObject *args)
  164. {
  165.   volatile struct gdb_exception except;
  166.   PyObject *result = NULL;

  167.   TRY_CATCH (except, RETURN_MASK_ALL)
  168.     {
  169.       struct value *self_val, *res_val;
  170.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());

  171.       self_val = ((value_object *) self)->value;
  172.       switch (TYPE_CODE (check_typedef (value_type (self_val))))
  173.         {
  174.         case TYPE_CODE_PTR:
  175.           res_val = value_ind (self_val);
  176.           break;
  177.         case TYPE_CODE_REF:
  178.           res_val = coerce_ref (self_val);
  179.           break;
  180.         default:
  181.           error(_("Trying to get the referenced value from a value which is "
  182.                   "neither a pointer nor a reference."));
  183.         }

  184.       result = value_to_value_object (res_val);
  185.       do_cleanups (cleanup);
  186.     }
  187.   GDB_PY_HANDLE_EXCEPTION (except);

  188.   return result;
  189. }

  190. /* Return "&value".  */
  191. static PyObject *
  192. valpy_get_address (PyObject *self, void *closure)
  193. {
  194.   value_object *val_obj = (value_object *) self;
  195.   volatile struct gdb_exception except;

  196.   if (!val_obj->address)
  197.     {
  198.       TRY_CATCH (except, RETURN_MASK_ALL)
  199.         {
  200.           struct value *res_val;
  201.           struct cleanup *cleanup
  202.             = make_cleanup_value_free_to_mark (value_mark ());

  203.           res_val = value_addr (val_obj->value);
  204.           val_obj->address = value_to_value_object (res_val);
  205.           do_cleanups (cleanup);
  206.         }
  207.       if (except.reason < 0)
  208.         {
  209.           val_obj->address = Py_None;
  210.           Py_INCREF (Py_None);
  211.         }
  212.     }

  213.   Py_XINCREF (val_obj->address);

  214.   return val_obj->address;
  215. }

  216. /* Return type of the value.  */
  217. static PyObject *
  218. valpy_get_type (PyObject *self, void *closure)
  219. {
  220.   value_object *obj = (value_object *) self;

  221.   if (!obj->type)
  222.     {
  223.       obj->type = type_to_type_object (value_type (obj->value));
  224.       if (!obj->type)
  225.         return NULL;
  226.     }
  227.   Py_INCREF (obj->type);
  228.   return obj->type;
  229. }

  230. /* Return dynamic type of the value.  */

  231. static PyObject *
  232. valpy_get_dynamic_type (PyObject *self, void *closure)
  233. {
  234.   value_object *obj = (value_object *) self;
  235.   volatile struct gdb_exception except;
  236.   struct type *type = NULL;

  237.   if (obj->dynamic_type != NULL)
  238.     {
  239.       Py_INCREF (obj->dynamic_type);
  240.       return obj->dynamic_type;
  241.     }

  242.   TRY_CATCH (except, RETURN_MASK_ALL)
  243.     {
  244.       struct value *val = obj->value;
  245.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());

  246.       type = value_type (val);
  247.       CHECK_TYPEDEF (type);

  248.       if (((TYPE_CODE (type) == TYPE_CODE_PTR)
  249.            || (TYPE_CODE (type) == TYPE_CODE_REF))
  250.           && (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_STRUCT))
  251.         {
  252.           struct value *target;
  253.           int was_pointer = TYPE_CODE (type) == TYPE_CODE_PTR;

  254.           if (was_pointer)
  255.             target = value_ind (val);
  256.           else
  257.             target = coerce_ref (val);
  258.           type = value_rtti_type (target, NULL, NULL, NULL);

  259.           if (type)
  260.             {
  261.               if (was_pointer)
  262.                 type = lookup_pointer_type (type);
  263.               else
  264.                 type = lookup_reference_type (type);
  265.             }
  266.         }
  267.       else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
  268.         type = value_rtti_type (val, NULL, NULL, NULL);
  269.       else
  270.         {
  271.           /* Re-use object's static type.  */
  272.           type = NULL;
  273.         }

  274.       do_cleanups (cleanup);
  275.     }
  276.   GDB_PY_HANDLE_EXCEPTION (except);

  277.   if (type == NULL)
  278.     obj->dynamic_type = valpy_get_type (self, NULL);
  279.   else
  280.     obj->dynamic_type = type_to_type_object (type);

  281.   Py_XINCREF (obj->dynamic_type);
  282.   return obj->dynamic_type;
  283. }

  284. /* Implementation of gdb.Value.lazy_string ([encoding] [, length]) ->
  285.    string.  Return a PyObject representing a lazy_string_object type.
  286.    A lazy string is a pointer to a string with an optional encoding and
  287.    length.  If ENCODING is not given, encoding is set to None.  If an
  288.    ENCODING is provided the encoding parameter is set to ENCODING, but
  289.    the string is not encoded.  If LENGTH is provided then the length
  290.    parameter is set to LENGTH, otherwise length will be set to -1 (first
  291.    null of appropriate with).  */
  292. static PyObject *
  293. valpy_lazy_string (PyObject *self, PyObject *args, PyObject *kw)
  294. {
  295.   gdb_py_longest length = -1;
  296.   struct value *value = ((value_object *) self)->value;
  297.   const char *user_encoding = NULL;
  298.   static char *keywords[] = { "encoding", "length", NULL };
  299.   PyObject *str_obj = NULL;
  300.   volatile struct gdb_exception except;

  301.   if (!PyArg_ParseTupleAndKeywords (args, kw, "|s" GDB_PY_LL_ARG, keywords,
  302.                                     &user_encoding, &length))
  303.     return NULL;

  304.   TRY_CATCH (except, RETURN_MASK_ALL)
  305.     {
  306.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());

  307.       if (TYPE_CODE (value_type (value)) == TYPE_CODE_PTR)
  308.         value = value_ind (value);

  309.       str_obj = gdbpy_create_lazy_string_object (value_address (value), length,
  310.                                                  user_encoding,
  311.                                                  value_type (value));

  312.       do_cleanups (cleanup);
  313.     }
  314.   GDB_PY_HANDLE_EXCEPTION (except);

  315.   return str_obj;
  316. }

  317. /* Implementation of gdb.Value.string ([encoding] [, errors]
  318.    [, length]) -> string.  Return Unicode string with value contents.
  319.    If ENCODING is not given, the string is assumed to be encoded in
  320.    the target's charset.  If LENGTH is provided, only fetch string to
  321.    the length provided.  */

  322. static PyObject *
  323. valpy_string (PyObject *self, PyObject *args, PyObject *kw)
  324. {
  325.   int length = -1;
  326.   gdb_byte *buffer;
  327.   struct value *value = ((value_object *) self)->value;
  328.   volatile struct gdb_exception except;
  329.   PyObject *unicode;
  330.   const char *encoding = NULL;
  331.   const char *errors = NULL;
  332.   const char *user_encoding = NULL;
  333.   const char *la_encoding = NULL;
  334.   struct type *char_type;
  335.   static char *keywords[] = { "encoding", "errors", "length", NULL };

  336.   if (!PyArg_ParseTupleAndKeywords (args, kw, "|ssi", keywords,
  337.                                     &user_encoding, &errors, &length))
  338.     return NULL;

  339.   TRY_CATCH (except, RETURN_MASK_ALL)
  340.     {
  341.       LA_GET_STRING (value, &buffer, &length, &char_type, &la_encoding);
  342.     }
  343.   GDB_PY_HANDLE_EXCEPTION (except);

  344.   encoding = (user_encoding && *user_encoding) ? user_encoding : la_encoding;
  345.   unicode = PyUnicode_Decode ((const char *) buffer,
  346.                               length * TYPE_LENGTH (char_type),
  347.                               encoding, errors);
  348.   xfree (buffer);

  349.   return unicode;
  350. }

  351. /* A helper function that implements the various cast operators.  */

  352. static PyObject *
  353. valpy_do_cast (PyObject *self, PyObject *args, enum exp_opcode op)
  354. {
  355.   PyObject *type_obj, *result = NULL;
  356.   struct type *type;
  357.   volatile struct gdb_exception except;

  358.   if (! PyArg_ParseTuple (args, "O", &type_obj))
  359.     return NULL;

  360.   type = type_object_to_type (type_obj);
  361.   if (! type)
  362.     {
  363.       PyErr_SetString (PyExc_RuntimeError,
  364.                        _("Argument must be a type."));
  365.       return NULL;
  366.     }

  367.   TRY_CATCH (except, RETURN_MASK_ALL)
  368.     {
  369.       struct value *val = ((value_object *) self)->value;
  370.       struct value *res_val;
  371.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());

  372.       if (op == UNOP_DYNAMIC_CAST)
  373.         res_val = value_dynamic_cast (type, val);
  374.       else if (op == UNOP_REINTERPRET_CAST)
  375.         res_val = value_reinterpret_cast (type, val);
  376.       else
  377.         {
  378.           gdb_assert (op == UNOP_CAST);
  379.           res_val = value_cast (type, val);
  380.         }

  381.       result = value_to_value_object (res_val);
  382.       do_cleanups (cleanup);
  383.     }
  384.   GDB_PY_HANDLE_EXCEPTION (except);

  385.   return result;
  386. }

  387. /* Implementation of the "cast" method.  */

  388. static PyObject *
  389. valpy_cast (PyObject *self, PyObject *args)
  390. {
  391.   return valpy_do_cast (self, args, UNOP_CAST);
  392. }

  393. /* Implementation of the "dynamic_cast" method.  */

  394. static PyObject *
  395. valpy_dynamic_cast (PyObject *self, PyObject *args)
  396. {
  397.   return valpy_do_cast (self, args, UNOP_DYNAMIC_CAST);
  398. }

  399. /* Implementation of the "reinterpret_cast" method.  */

  400. static PyObject *
  401. valpy_reinterpret_cast (PyObject *self, PyObject *args)
  402. {
  403.   return valpy_do_cast (self, args, UNOP_REINTERPRET_CAST);
  404. }

  405. static Py_ssize_t
  406. valpy_length (PyObject *self)
  407. {
  408.   /* We don't support getting the number of elements in a struct / class.  */
  409.   PyErr_SetString (PyExc_NotImplementedError,
  410.                    _("Invalid operation on gdb.Value."));
  411.   return -1;
  412. }

  413. /* Return 1 if the gdb.Field object FIELD is present in the value V.
  414.    Returns 0 otherwise.  If any Python error occurs, -1 is returned.  */

  415. static int
  416. value_has_field (struct value *v, PyObject *field)
  417. {
  418.   struct type *parent_type, *val_type;
  419.   enum type_code type_code;
  420.   PyObject *type_object = PyObject_GetAttrString (field, "parent_type");
  421.   volatile struct gdb_exception except;
  422.   int has_field = 0;

  423.   if (type_object == NULL)
  424.     return -1;

  425.   parent_type = type_object_to_type (type_object);
  426.   Py_DECREF (type_object);
  427.   if (parent_type == NULL)
  428.     {
  429.       PyErr_SetString (PyExc_TypeError,
  430.                        _("'parent_type' attribute of gdb.Field object is not a"
  431.                          "gdb.Type object."));
  432.       return -1;
  433.     }

  434.   TRY_CATCH (except, RETURN_MASK_ALL)
  435.     {
  436.       val_type = value_type (v);
  437.       val_type = check_typedef (val_type);
  438.       if (TYPE_CODE (val_type) == TYPE_CODE_REF
  439.           || TYPE_CODE (val_type) == TYPE_CODE_PTR)
  440.       val_type = check_typedef (TYPE_TARGET_TYPE (val_type));

  441.       type_code = TYPE_CODE (val_type);
  442.       if ((type_code == TYPE_CODE_STRUCT || type_code == TYPE_CODE_UNION)
  443.           && types_equal (val_type, parent_type))
  444.         has_field = 1;
  445.       else
  446.         has_field = 0;
  447.     }
  448.   GDB_PY_SET_HANDLE_EXCEPTION (except);

  449.   return has_field;
  450. }

  451. /* Return the value of a flag FLAG_NAME in a gdb.Field object FIELD.
  452.    Returns 1 if the flag value is true, 0 if it is false, and -1 if
  453.    a Python error occurs.  */

  454. static int
  455. get_field_flag (PyObject *field, const char *flag_name)
  456. {
  457.   int flag_value;
  458.   PyObject *flag_object = PyObject_GetAttrString (field, flag_name);

  459.   if (flag_object == NULL)
  460.     return -1;

  461.   flag_value = PyObject_IsTrue (flag_object);
  462.   Py_DECREF (flag_object);

  463.   return flag_value;
  464. }

  465. /* Return the "type" attribute of a gdb.Field object.
  466.    Returns NULL on error, with a Python exception set.  */

  467. static struct type *
  468. get_field_type (PyObject *field)
  469. {
  470.   PyObject *ftype_obj = PyObject_GetAttrString (field, "type");
  471.   struct type *ftype;

  472.   if (ftype_obj == NULL)
  473.     return NULL;
  474.   ftype = type_object_to_type (ftype_obj);
  475.   Py_DECREF (ftype_obj);
  476.   if (ftype == NULL)
  477.     PyErr_SetString (PyExc_TypeError,
  478.                      _("'type' attribute of gdb.Field object is not a "
  479.                        "gdb.Type object."));

  480.   return ftype;
  481. }

  482. /* Given string name or a gdb.Field object corresponding to an element inside
  483.    a structure, return its value object.  Returns NULL on error, with a python
  484.    exception set.  */

  485. static PyObject *
  486. valpy_getitem (PyObject *self, PyObject *key)
  487. {
  488.   value_object *self_value = (value_object *) self;
  489.   char *field = NULL;
  490.   struct type *base_class_type = NULL, *field_type = NULL;
  491.   long bitpos = -1;
  492.   volatile struct gdb_exception except;
  493.   PyObject *result = NULL;

  494.   if (gdbpy_is_string (key))
  495.     {
  496.       field = python_string_to_host_string (key);
  497.       if (field == NULL)
  498.         return NULL;
  499.     }
  500.   else if (gdbpy_is_field (key))
  501.     {
  502.       int is_base_class, valid_field;

  503.       valid_field = value_has_field (self_value->value, key);
  504.       if (valid_field < 0)
  505.         return NULL;
  506.       else if (valid_field == 0)
  507.         {
  508.           PyErr_SetString (PyExc_TypeError,
  509.                            _("Invalid lookup for a field not contained in "
  510.                              "the value."));

  511.           return NULL;
  512.         }

  513.       is_base_class = get_field_flag (key, "is_base_class");
  514.       if (is_base_class < 0)
  515.         return NULL;
  516.       else if (is_base_class > 0)
  517.         {
  518.           base_class_type = get_field_type (key);
  519.           if (base_class_type == NULL)
  520.             return NULL;
  521.         }
  522.       else
  523.         {
  524.           PyObject *name_obj = PyObject_GetAttrString (key, "name");

  525.           if (name_obj == NULL)
  526.             return NULL;

  527.           if (name_obj != Py_None)
  528.             {
  529.               field = python_string_to_host_string (name_obj);
  530.               Py_DECREF (name_obj);
  531.               if (field == NULL)
  532.                 return NULL;
  533.             }
  534.           else
  535.             {
  536.               PyObject *bitpos_obj;
  537.               int valid;

  538.               Py_DECREF (name_obj);

  539.               if (!PyObject_HasAttrString (key, "bitpos"))
  540.                 {
  541.                   PyErr_SetString (PyExc_AttributeError,
  542.                                    _("gdb.Field object has no name and no "
  543.                                      "'bitpos' attribute."));

  544.                   return NULL;
  545.                 }
  546.               bitpos_obj = PyObject_GetAttrString (key, "bitpos");
  547.               if (bitpos_obj == NULL)
  548.                 return NULL;
  549.               valid = gdb_py_int_as_long (bitpos_obj, &bitpos);
  550.               Py_DECREF (bitpos_obj);
  551.               if (!valid)
  552.                 return NULL;

  553.               field_type = get_field_type (key);
  554.               if (field_type == NULL)
  555.                 return NULL;
  556.             }
  557.         }
  558.     }

  559.   TRY_CATCH (except, RETURN_MASK_ALL)
  560.     {
  561.       struct value *tmp = self_value->value;
  562.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
  563.       struct value *res_val = NULL;

  564.       if (field)
  565.         res_val = value_struct_elt (&tmp, NULL, field, 0, NULL);
  566.       else if (bitpos >= 0)
  567.         res_val = value_struct_elt_bitpos (&tmp, bitpos, field_type,
  568.                                            "struct/class/union");
  569.       else if (base_class_type != NULL)
  570.         {
  571.           struct type *val_type;

  572.           val_type = check_typedef (value_type (tmp));
  573.           if (TYPE_CODE (val_type) == TYPE_CODE_PTR)
  574.             res_val = value_cast (lookup_pointer_type (base_class_type), tmp);
  575.           else if (TYPE_CODE (val_type) == TYPE_CODE_REF)
  576.             res_val = value_cast (lookup_reference_type (base_class_type), tmp);
  577.           else
  578.             res_val = value_cast (base_class_type, tmp);
  579.         }
  580.       else
  581.         {
  582.           /* Assume we are attempting an array access, and let the
  583.              value code throw an exception if the index has an invalid
  584.              type.  */
  585.           struct value *idx = convert_value_from_python (key);

  586.           if (idx != NULL)
  587.             {
  588.               /* Check the value's type is something that can be accessed via
  589.                  a subscript.  */
  590.               struct type *type;

  591.               tmp = coerce_ref (tmp);
  592.               type = check_typedef (value_type (tmp));
  593.               if (TYPE_CODE (type) != TYPE_CODE_ARRAY
  594.                   && TYPE_CODE (type) != TYPE_CODE_PTR)
  595.                   error (_("Cannot subscript requested type."));
  596.               else
  597.                 res_val = value_subscript (tmp, value_as_long (idx));
  598.             }
  599.         }

  600.       if (res_val)
  601.         result = value_to_value_object (res_val);
  602.       do_cleanups (cleanup);
  603.     }

  604.   xfree (field);
  605.   GDB_PY_HANDLE_EXCEPTION (except);

  606.   return result;
  607. }

  608. static int
  609. valpy_setitem (PyObject *self, PyObject *key, PyObject *value)
  610. {
  611.   PyErr_Format (PyExc_NotImplementedError,
  612.                 _("Setting of struct elements is not currently supported."));
  613.   return -1;
  614. }

  615. /* Called by the Python interpreter to perform an inferior function
  616.    call on the value.  Returns NULL on error, with a python exception set.  */
  617. static PyObject *
  618. valpy_call (PyObject *self, PyObject *args, PyObject *keywords)
  619. {
  620.   Py_ssize_t args_count;
  621.   volatile struct gdb_exception except;
  622.   struct value *function = ((value_object *) self)->value;
  623.   struct value **vargs = NULL;
  624.   struct type *ftype = NULL;
  625.   struct value *mark = value_mark ();
  626.   PyObject *result = NULL;

  627.   TRY_CATCH (except, RETURN_MASK_ALL)
  628.     {
  629.       ftype = check_typedef (value_type (function));
  630.     }
  631.   GDB_PY_HANDLE_EXCEPTION (except);

  632.   if (TYPE_CODE (ftype) != TYPE_CODE_FUNC)
  633.     {
  634.       PyErr_SetString (PyExc_RuntimeError,
  635.                        _("Value is not callable (not TYPE_CODE_FUNC)."));
  636.       return NULL;
  637.     }

  638.   if (! PyTuple_Check (args))
  639.     {
  640.       PyErr_SetString (PyExc_TypeError,
  641.                        _("Inferior arguments must be provided in a tuple."));
  642.       return NULL;
  643.     }

  644.   args_count = PyTuple_Size (args);
  645.   if (args_count > 0)
  646.     {
  647.       int i;

  648.       vargs = alloca (sizeof (struct value *) * args_count);
  649.       for (i = 0; i < args_count; i++)
  650.         {
  651.           PyObject *item = PyTuple_GetItem (args, i);

  652.           if (item == NULL)
  653.             return NULL;

  654.           vargs[i] = convert_value_from_python (item);
  655.           if (vargs[i] == NULL)
  656.             return NULL;
  657.         }
  658.     }

  659.   TRY_CATCH (except, RETURN_MASK_ALL)
  660.     {
  661.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (mark);
  662.       struct value *return_value;

  663.       return_value = call_function_by_hand (function, args_count, vargs);
  664.       result = value_to_value_object (return_value);
  665.       do_cleanups (cleanup);
  666.     }
  667.   GDB_PY_HANDLE_EXCEPTION (except);

  668.   return result;
  669. }

  670. /* Called by the Python interpreter to obtain string representation
  671.    of the object.  */
  672. static PyObject *
  673. valpy_str (PyObject *self)
  674. {
  675.   char *s = NULL;
  676.   PyObject *result;
  677.   struct value_print_options opts;
  678.   volatile struct gdb_exception except;

  679.   get_user_print_options (&opts);
  680.   opts.deref_ref = 0;

  681.   TRY_CATCH (except, RETURN_MASK_ALL)
  682.     {
  683.       struct ui_file *stb = mem_fileopen ();
  684.       struct cleanup *old_chain = make_cleanup_ui_file_delete (stb);

  685.       common_val_print (((value_object *) self)->value, stb, 0,
  686.                         &opts, python_language);
  687.       s = ui_file_xstrdup (stb, NULL);

  688.       do_cleanups (old_chain);
  689.     }
  690.   GDB_PY_HANDLE_EXCEPTION (except);

  691.   result = PyUnicode_Decode (s, strlen (s), host_charset (), NULL);
  692.   xfree (s);

  693.   return result;
  694. }

  695. /* Implements gdb.Value.is_optimized_out.  */
  696. static PyObject *
  697. valpy_get_is_optimized_out (PyObject *self, void *closure)
  698. {
  699.   struct value *value = ((value_object *) self)->value;
  700.   int opt = 0;
  701.   volatile struct gdb_exception except;

  702.   TRY_CATCH (except, RETURN_MASK_ALL)
  703.     {
  704.       opt = value_optimized_out (value);
  705.     }
  706.   GDB_PY_HANDLE_EXCEPTION (except);

  707.   if (opt)
  708.     Py_RETURN_TRUE;

  709.   Py_RETURN_FALSE;
  710. }

  711. /* Implements gdb.Value.is_lazy.  */
  712. static PyObject *
  713. valpy_get_is_lazy (PyObject *self, void *closure)
  714. {
  715.   struct value *value = ((value_object *) self)->value;
  716.   int opt = 0;
  717.   volatile struct gdb_exception except;

  718.   TRY_CATCH (except, RETURN_MASK_ALL)
  719.     {
  720.       opt = value_lazy (value);
  721.     }
  722.   GDB_PY_HANDLE_EXCEPTION (except);

  723.   if (opt)
  724.     Py_RETURN_TRUE;

  725.   Py_RETURN_FALSE;
  726. }

  727. /* Implements gdb.Value.fetch_lazy ().  */
  728. static PyObject *
  729. valpy_fetch_lazy (PyObject *self, PyObject *args)
  730. {
  731.   struct value *value = ((value_object *) self)->value;
  732.   volatile struct gdb_exception except;

  733.   TRY_CATCH (except, RETURN_MASK_ALL)
  734.     {
  735.       if (value_lazy (value))
  736.         value_fetch_lazy (value);
  737.     }
  738.   GDB_PY_HANDLE_EXCEPTION (except);

  739.   Py_RETURN_NONE;
  740. }

  741. /* Calculate and return the address of the PyObject as the value of
  742.    the builtin __hash__ call.  */
  743. static long
  744. valpy_hash (PyObject *self)
  745. {
  746.   return (long) (intptr_t) self;
  747. }

  748. enum valpy_opcode
  749. {
  750.   VALPY_ADD,
  751.   VALPY_SUB,
  752.   VALPY_MUL,
  753.   VALPY_DIV,
  754.   VALPY_REM,
  755.   VALPY_POW,
  756.   VALPY_LSH,
  757.   VALPY_RSH,
  758.   VALPY_BITAND,
  759.   VALPY_BITOR,
  760.   VALPY_BITXOR
  761. };

  762. /* If TYPE is a reference, return the target; otherwise return TYPE.  */
  763. #define STRIP_REFERENCE(TYPE) \
  764.   ((TYPE_CODE (TYPE) == TYPE_CODE_REF) ? (TYPE_TARGET_TYPE (TYPE)) : (TYPE))

  765. /* Returns a value object which is the result of applying the operation
  766.    specified by OPCODE to the given arguments.  Returns NULL on error, with
  767.    a python exception set.  */
  768. static PyObject *
  769. valpy_binop (enum valpy_opcode opcode, PyObject *self, PyObject *other)
  770. {
  771.   volatile struct gdb_exception except;
  772.   PyObject *result = NULL;

  773.   TRY_CATCH (except, RETURN_MASK_ALL)
  774.     {
  775.       struct value *arg1, *arg2;
  776.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
  777.       struct value *res_val = NULL;
  778.       enum exp_opcode op = OP_NULL;
  779.       int handled = 0;

  780.       /* If the gdb.Value object is the second operand, then it will be passed
  781.          to us as the OTHER argument, and SELF will be an entirely different
  782.          kind of object, altogether.  Because of this, we can't assume self is
  783.          a gdb.Value object and need to convert it from python as well.  */
  784.       arg1 = convert_value_from_python (self);
  785.       if (arg1 == NULL)
  786.         {
  787.           do_cleanups (cleanup);
  788.           break;
  789.         }

  790.       arg2 = convert_value_from_python (other);
  791.       if (arg2 == NULL)
  792.         {
  793.           do_cleanups (cleanup);
  794.           break;
  795.         }

  796.       switch (opcode)
  797.         {
  798.         case VALPY_ADD:
  799.           {
  800.             struct type *ltype = value_type (arg1);
  801.             struct type *rtype = value_type (arg2);

  802.             CHECK_TYPEDEF (ltype);
  803.             ltype = STRIP_REFERENCE (ltype);
  804.             CHECK_TYPEDEF (rtype);
  805.             rtype = STRIP_REFERENCE (rtype);

  806.             handled = 1;
  807.             if (TYPE_CODE (ltype) == TYPE_CODE_PTR
  808.                 && is_integral_type (rtype))
  809.               res_val = value_ptradd (arg1, value_as_long (arg2));
  810.             else if (TYPE_CODE (rtype) == TYPE_CODE_PTR
  811.                      && is_integral_type (ltype))
  812.               res_val = value_ptradd (arg2, value_as_long (arg1));
  813.             else
  814.               {
  815.                 handled = 0;
  816.                 op = BINOP_ADD;
  817.               }
  818.           }
  819.           break;
  820.         case VALPY_SUB:
  821.           {
  822.             struct type *ltype = value_type (arg1);
  823.             struct type *rtype = value_type (arg2);

  824.             CHECK_TYPEDEF (ltype);
  825.             ltype = STRIP_REFERENCE (ltype);
  826.             CHECK_TYPEDEF (rtype);
  827.             rtype = STRIP_REFERENCE (rtype);

  828.             handled = 1;
  829.             if (TYPE_CODE (ltype) == TYPE_CODE_PTR
  830.                 && TYPE_CODE (rtype) == TYPE_CODE_PTR)
  831.               /* A ptrdiff_t for the target would be preferable here.  */
  832.               res_val = value_from_longest (builtin_type_pyint,
  833.                                             value_ptrdiff (arg1, arg2));
  834.             else if (TYPE_CODE (ltype) == TYPE_CODE_PTR
  835.                      && is_integral_type (rtype))
  836.               res_val = value_ptradd (arg1, - value_as_long (arg2));
  837.             else
  838.               {
  839.                 handled = 0;
  840.                 op = BINOP_SUB;
  841.               }
  842.           }
  843.           break;
  844.         case VALPY_MUL:
  845.           op = BINOP_MUL;
  846.           break;
  847.         case VALPY_DIV:
  848.           op = BINOP_DIV;
  849.           break;
  850.         case VALPY_REM:
  851.           op = BINOP_REM;
  852.           break;
  853.         case VALPY_POW:
  854.           op = BINOP_EXP;
  855.           break;
  856.         case VALPY_LSH:
  857.           op = BINOP_LSH;
  858.           break;
  859.         case VALPY_RSH:
  860.           op = BINOP_RSH;
  861.           break;
  862.         case VALPY_BITAND:
  863.           op = BINOP_BITWISE_AND;
  864.           break;
  865.         case VALPY_BITOR:
  866.           op = BINOP_BITWISE_IOR;
  867.           break;
  868.         case VALPY_BITXOR:
  869.           op = BINOP_BITWISE_XOR;
  870.           break;
  871.         }

  872.       if (!handled)
  873.         {
  874.           if (binop_user_defined_p (op, arg1, arg2))
  875.             res_val = value_x_binop (arg1, arg2, op, OP_NULL, EVAL_NORMAL);
  876.           else
  877.             res_val = value_binop (arg1, arg2, op);
  878.         }

  879.       if (res_val)
  880.         result = value_to_value_object (res_val);

  881.       do_cleanups (cleanup);
  882.     }
  883.   GDB_PY_HANDLE_EXCEPTION (except);

  884.   return result;
  885. }

  886. static PyObject *
  887. valpy_add (PyObject *self, PyObject *other)
  888. {
  889.   return valpy_binop (VALPY_ADD, self, other);
  890. }

  891. static PyObject *
  892. valpy_subtract (PyObject *self, PyObject *other)
  893. {
  894.   return valpy_binop (VALPY_SUB, self, other);
  895. }

  896. static PyObject *
  897. valpy_multiply (PyObject *self, PyObject *other)
  898. {
  899.   return valpy_binop (VALPY_MUL, self, other);
  900. }

  901. static PyObject *
  902. valpy_divide (PyObject *self, PyObject *other)
  903. {
  904.   return valpy_binop (VALPY_DIV, self, other);
  905. }

  906. static PyObject *
  907. valpy_remainder (PyObject *self, PyObject *other)
  908. {
  909.   return valpy_binop (VALPY_REM, self, other);
  910. }

  911. static PyObject *
  912. valpy_power (PyObject *self, PyObject *other, PyObject *unused)
  913. {
  914.   /* We don't support the ternary form of pow.  I don't know how to express
  915.      that, so let's just throw NotImplementedError to at least do something
  916.      about it.  */
  917.   if (unused != Py_None)
  918.     {
  919.       PyErr_SetString (PyExc_NotImplementedError,
  920.                        "Invalid operation on gdb.Value.");
  921.       return NULL;
  922.     }

  923.   return valpy_binop (VALPY_POW, self, other);
  924. }

  925. static PyObject *
  926. valpy_negative (PyObject *self)
  927. {
  928.   volatile struct gdb_exception except;
  929.   PyObject *result = NULL;

  930.   TRY_CATCH (except, RETURN_MASK_ALL)
  931.     {
  932.       /* Perhaps overkill, but consistency has some virtue.  */
  933.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());
  934.       struct value *val;

  935.       val = value_neg (((value_object *) self)->value);
  936.       result = value_to_value_object (val);
  937.       do_cleanups (cleanup);
  938.     }
  939.   GDB_PY_HANDLE_EXCEPTION (except);

  940.   return result;
  941. }

  942. static PyObject *
  943. valpy_positive (PyObject *self)
  944. {
  945.   return value_to_value_object (((value_object *) self)->value);
  946. }

  947. static PyObject *
  948. valpy_absolute (PyObject *self)
  949. {
  950.   struct value *value = ((value_object *) self)->value;
  951.   volatile struct gdb_exception except;
  952.   int isabs = 1;

  953.   TRY_CATCH (except, RETURN_MASK_ALL)
  954.     {
  955.       struct cleanup *cleanup = make_cleanup_value_free_to_mark (value_mark ());

  956.       if (value_less (value, value_zero (value_type (value), not_lval)))
  957.         isabs = 0;

  958.       do_cleanups (cleanup);
  959.     }
  960.   GDB_PY_HANDLE_EXCEPTION (except);

  961.   if (isabs)
  962.     return valpy_positive (self);
  963.   else
  964.     return valpy_negative (self);
  965. }

  966. /* Implements boolean evaluation of gdb.Value.  */
  967. static int
  968. valpy_nonzero (PyObject *self)
  969. {
  970.   volatile struct gdb_exception except;
  971.   value_object *self_value = (value_object *) self;
  972.   struct type *type;
  973.   int nonzero = 0; /* Appease GCC warning.  */

  974.   TRY_CATCH (except, RETURN_MASK_ALL)
  975.     {
  976.       type = check_typedef (value_type (self_value->value));

  977.       if (is_integral_type (type) || TYPE_CODE (type) == TYPE_CODE_PTR)
  978.         nonzero = !!value_as_long (self_value->value);
  979.       else if (TYPE_CODE (type) == TYPE_CODE_FLT)
  980.         nonzero = value_as_double (self_value->value) != 0;
  981.       else if (TYPE_CODE (type) == TYPE_CODE_DECFLOAT)
  982.         nonzero = !decimal_is_zero (value_contents (self_value->value),
  983.                                  TYPE_LENGTH (type),
  984.                                  gdbarch_byte_order (get_type_arch (type)));
  985.       else
  986.         /* All other values are True.  */
  987.         nonzero = 1;
  988.     }
  989.   /* This is not documented in the Python documentation, but if this
  990.      function fails, return -1 as slot_nb_nonzero does (the default
  991.      Python nonzero function).  */
  992.   GDB_PY_SET_HANDLE_EXCEPTION (except);

  993.   return nonzero;
  994. }

  995. /* Implements ~ for value objects.  */
  996. static PyObject *
  997. valpy_invert (PyObject *self)
  998. {
  999.   struct value *val = NULL;
  1000.   volatile struct gdb_exception except;

  1001.   TRY_CATCH (except, RETURN_MASK_ALL)
  1002.     {
  1003.       val = value_complement (((value_object *) self)->value);
  1004.     }
  1005.   GDB_PY_HANDLE_EXCEPTION (except);

  1006.   return value_to_value_object (val);
  1007. }

  1008. /* Implements left shift for value objects.  */
  1009. static PyObject *
  1010. valpy_lsh (PyObject *self, PyObject *other)
  1011. {
  1012.   return valpy_binop (VALPY_LSH, self, other);
  1013. }

  1014. /* Implements right shift for value objects.  */
  1015. static PyObject *
  1016. valpy_rsh (PyObject *self, PyObject *other)
  1017. {
  1018.   return valpy_binop (VALPY_RSH, self, other);
  1019. }

  1020. /* Implements bitwise and for value objects.  */
  1021. static PyObject *
  1022. valpy_and (PyObject *self, PyObject *other)
  1023. {
  1024.   return valpy_binop (VALPY_BITAND, self, other);
  1025. }

  1026. /* Implements bitwise or for value objects.  */
  1027. static PyObject *
  1028. valpy_or (PyObject *self, PyObject *other)
  1029. {
  1030.   return valpy_binop (VALPY_BITOR, self, other);
  1031. }

  1032. /* Implements bitwise xor for value objects.  */
  1033. static PyObject *
  1034. valpy_xor (PyObject *self, PyObject *other)
  1035. {
  1036.   return valpy_binop (VALPY_BITXOR, self, other);
  1037. }

  1038. /* Implements comparison operations for value objects.  Returns NULL on error,
  1039.    with a python exception set.  */
  1040. static PyObject *
  1041. valpy_richcompare (PyObject *self, PyObject *other, int op)
  1042. {
  1043.   int result = 0;
  1044.   volatile struct gdb_exception except;

  1045.   if (other == Py_None)
  1046.     /* Comparing with None is special.  From what I can tell, in Python
  1047.        None is smaller than anything else.  */
  1048.     switch (op) {
  1049.       case Py_LT:
  1050.       case Py_LE:
  1051.       case Py_EQ:
  1052.         Py_RETURN_FALSE;
  1053.       case Py_NE:
  1054.       case Py_GT:
  1055.       case Py_GE:
  1056.         Py_RETURN_TRUE;
  1057.       default:
  1058.         /* Can't happen.  */
  1059.         PyErr_SetString (PyExc_NotImplementedError,
  1060.                          _("Invalid operation on gdb.Value."));
  1061.         return NULL;
  1062.     }

  1063.   TRY_CATCH (except, RETURN_MASK_ALL)
  1064.     {
  1065.       struct value *value_other, *mark = value_mark ();
  1066.       struct cleanup *cleanup;

  1067.       value_other = convert_value_from_python (other);
  1068.       if (value_other == NULL)
  1069.         {
  1070.           result = -1;
  1071.           break;
  1072.         }

  1073.       cleanup = make_cleanup_value_free_to_mark (mark);

  1074.       switch (op) {
  1075.         case Py_LT:
  1076.           result = value_less (((value_object *) self)->value, value_other);
  1077.           break;
  1078.         case Py_LE:
  1079.           result = value_less (((value_object *) self)->value, value_other)
  1080.             || value_equal (((value_object *) self)->value, value_other);
  1081.           break;
  1082.         case Py_EQ:
  1083.           result = value_equal (((value_object *) self)->value, value_other);
  1084.           break;
  1085.         case Py_NE:
  1086.           result = !value_equal (((value_object *) self)->value, value_other);
  1087.           break;
  1088.         case Py_GT:
  1089.           result = value_less (value_other, ((value_object *) self)->value);
  1090.           break;
  1091.         case Py_GE:
  1092.           result = value_less (value_other, ((value_object *) self)->value)
  1093.             || value_equal (((value_object *) self)->value, value_other);
  1094.           break;
  1095.         default:
  1096.           /* Can't happen.  */
  1097.           PyErr_SetString (PyExc_NotImplementedError,
  1098.                            _("Invalid operation on gdb.Value."));
  1099.           result = -1;
  1100.           break;
  1101.       }

  1102.       do_cleanups (cleanup);
  1103.     }
  1104.   GDB_PY_HANDLE_EXCEPTION (except);

  1105.   /* In this case, the Python exception has already been set.  */
  1106.   if (result < 0)
  1107.     return NULL;

  1108.   if (result == 1)
  1109.     Py_RETURN_TRUE;

  1110.   Py_RETURN_FALSE;
  1111. }

  1112. #ifndef IS_PY3K
  1113. /* Implements conversion to int.  */
  1114. static PyObject *
  1115. valpy_int (PyObject *self)
  1116. {
  1117.   struct value *value = ((value_object *) self)->value;
  1118.   struct type *type = value_type (value);
  1119.   LONGEST l = 0;
  1120.   volatile struct gdb_exception except;

  1121.   TRY_CATCH (except, RETURN_MASK_ALL)
  1122.     {
  1123.       if (!is_integral_type (type))
  1124.         error (_("Cannot convert value to int."));

  1125.       l = value_as_long (value);
  1126.     }
  1127.   GDB_PY_HANDLE_EXCEPTION (except);

  1128.   return gdb_py_object_from_longest (l);
  1129. }
  1130. #endif

  1131. /* Implements conversion to long.  */
  1132. static PyObject *
  1133. valpy_long (PyObject *self)
  1134. {
  1135.   struct value *value = ((value_object *) self)->value;
  1136.   struct type *type = value_type (value);
  1137.   LONGEST l = 0;
  1138.   volatile struct gdb_exception except;

  1139.   TRY_CATCH (except, RETURN_MASK_ALL)
  1140.     {
  1141.       CHECK_TYPEDEF (type);

  1142.       if (!is_integral_type (type)
  1143.           && TYPE_CODE (type) != TYPE_CODE_PTR)
  1144.         error (_("Cannot convert value to long."));

  1145.       l = value_as_long (value);
  1146.     }
  1147.   GDB_PY_HANDLE_EXCEPTION (except);

  1148.   return gdb_py_long_from_longest (l);
  1149. }

  1150. /* Implements conversion to float.  */
  1151. static PyObject *
  1152. valpy_float (PyObject *self)
  1153. {
  1154.   struct value *value = ((value_object *) self)->value;
  1155.   struct type *type = value_type (value);
  1156.   double d = 0;
  1157.   volatile struct gdb_exception except;

  1158.   TRY_CATCH (except, RETURN_MASK_ALL)
  1159.     {
  1160.       CHECK_TYPEDEF (type);

  1161.       if (TYPE_CODE (type) != TYPE_CODE_FLT)
  1162.         error (_("Cannot convert value to float."));

  1163.       d = value_as_double (value);
  1164.     }
  1165.   GDB_PY_HANDLE_EXCEPTION (except);

  1166.   return PyFloat_FromDouble (d);
  1167. }

  1168. /* Returns an object for a value which is released from the all_values chain,
  1169.    so its lifetime is not bound to the execution of a command.  */
  1170. PyObject *
  1171. value_to_value_object (struct value *val)
  1172. {
  1173.   value_object *val_obj;

  1174.   val_obj = PyObject_New (value_object, &value_object_type);
  1175.   if (val_obj != NULL)
  1176.     {
  1177.       val_obj->value = val;
  1178.       release_value_or_incref (val);
  1179.       val_obj->address = NULL;
  1180.       val_obj->type = NULL;
  1181.       val_obj->dynamic_type = NULL;
  1182.       note_value (val_obj);
  1183.     }

  1184.   return (PyObject *) val_obj;
  1185. }

  1186. /* Returns a borrowed reference to the struct value corresponding to
  1187.    the given value object.  */
  1188. struct value *
  1189. value_object_to_value (PyObject *self)
  1190. {
  1191.   value_object *real;

  1192.   if (! PyObject_TypeCheck (self, &value_object_type))
  1193.     return NULL;
  1194.   real = (value_object *) self;
  1195.   return real->value;
  1196. }

  1197. /* Try to convert a Python value to a gdb value.  If the value cannot
  1198.    be converted, set a Python exception and return NULL.  Returns a
  1199.    reference to a new value on the all_values chain.  */

  1200. struct value *
  1201. convert_value_from_python (PyObject *obj)
  1202. {
  1203.   struct value *value = NULL; /* -Wall */
  1204.   volatile struct gdb_exception except;
  1205.   int cmp;

  1206.   gdb_assert (obj != NULL);

  1207.   TRY_CATCH (except, RETURN_MASK_ALL)
  1208.     {
  1209.       if (PyBool_Check (obj))
  1210.         {
  1211.           cmp = PyObject_IsTrue (obj);
  1212.           if (cmp >= 0)
  1213.             value = value_from_longest (builtin_type_pybool, cmp);
  1214.         }
  1215.       /* Make a long logic check first.  In Python 3.x, internally,
  1216.          all integers are represented as longs.  In Python 2.x, there
  1217.          is still a differentiation internally between a PyInt and a
  1218.          PyLong.  Explicitly do this long check conversion first. In
  1219.          GDB, for Python 3.x, we #ifdef PyInt = PyLong.  This check has
  1220.          to be done first to ensure we do not lose information in the
  1221.          conversion process.  */
  1222.       else if (PyLong_Check (obj))
  1223.         {
  1224.           LONGEST l = PyLong_AsLongLong (obj);

  1225.           if (PyErr_Occurred ())
  1226.             {
  1227.               /* If the error was an overflow, we can try converting to
  1228.                  ULONGEST instead.  */
  1229.               if (PyErr_ExceptionMatches (PyExc_OverflowError))
  1230.                 {
  1231.                   PyObject *etype, *evalue, *etraceback, *zero;

  1232.                   PyErr_Fetch (&etype, &evalue, &etraceback);
  1233.                   zero = PyInt_FromLong (0);

  1234.                   /* Check whether obj is positive.  */
  1235.                   if (PyObject_RichCompareBool (obj, zero, Py_GT) > 0)
  1236.                     {
  1237.                       ULONGEST ul;

  1238.                       ul = PyLong_AsUnsignedLongLong (obj);
  1239.                       if (! PyErr_Occurred ())
  1240.                         value = value_from_ulongest (builtin_type_upylong, ul);
  1241.                     }
  1242.                   else
  1243.                     /* There's nothing we can do.  */
  1244.                     PyErr_Restore (etype, evalue, etraceback);

  1245.                   Py_DECREF (zero);
  1246.                 }
  1247.             }
  1248.           else
  1249.             value = value_from_longest (builtin_type_pylong, l);
  1250.         }
  1251.       else if (PyInt_Check (obj))
  1252.         {
  1253.           long l = PyInt_AsLong (obj);

  1254.           if (! PyErr_Occurred ())
  1255.             value = value_from_longest (builtin_type_pyint, l);
  1256.         }
  1257.       else if (PyFloat_Check (obj))
  1258.         {
  1259.           double d = PyFloat_AsDouble (obj);

  1260.           if (! PyErr_Occurred ())
  1261.             value = value_from_double (builtin_type_pyfloat, d);
  1262.         }
  1263.       else if (gdbpy_is_string (obj))
  1264.         {
  1265.           char *s;

  1266.           s = python_string_to_target_string (obj);
  1267.           if (s != NULL)
  1268.             {
  1269.               struct cleanup *old;

  1270.               old = make_cleanup (xfree, s);
  1271.               value = value_cstring (s, strlen (s), builtin_type_pychar);
  1272.               do_cleanups (old);
  1273.             }
  1274.         }
  1275.       else if (PyObject_TypeCheck (obj, &value_object_type))
  1276.         value = value_copy (((value_object *) obj)->value);
  1277.       else if (gdbpy_is_lazy_string (obj))
  1278.         {
  1279.           PyObject *result;

  1280.           result = PyObject_CallMethodObjArgs (obj, gdbpy_value_cstNULL);
  1281.           value = value_copy (((value_object *) result)->value);
  1282.         }
  1283.       else
  1284. #ifdef IS_PY3K
  1285.         PyErr_Format (PyExc_TypeError,
  1286.                       _("Could not convert Python object: %S."), obj);
  1287. #else
  1288.         PyErr_Format (PyExc_TypeError,
  1289.                       _("Could not convert Python object: %s."),
  1290.                       PyString_AsString (PyObject_Str (obj)));
  1291. #endif
  1292.     }
  1293.   if (except.reason < 0)
  1294.     {
  1295.       PyErr_Format (except.reason == RETURN_QUIT
  1296.                     ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
  1297.                     "%s", except.message);
  1298.       return NULL;
  1299.     }

  1300.   return value;
  1301. }

  1302. /* Returns value object in the ARGth position in GDB's history.  */
  1303. PyObject *
  1304. gdbpy_history (PyObject *self, PyObject *args)
  1305. {
  1306.   int i;
  1307.   struct value *res_val = NULL;          /* Initialize to appease gcc warning.  */
  1308.   volatile struct gdb_exception except;

  1309.   if (!PyArg_ParseTuple (args, "i", &i))
  1310.     return NULL;

  1311.   TRY_CATCH (except, RETURN_MASK_ALL)
  1312.     {
  1313.       res_val = access_value_history (i);
  1314.     }
  1315.   GDB_PY_HANDLE_EXCEPTION (except);

  1316.   return value_to_value_object (res_val);
  1317. }

  1318. /* Returns 1 in OBJ is a gdb.Value object, 0 otherwise.  */

  1319. int
  1320. gdbpy_is_value_object (PyObject *obj)
  1321. {
  1322.   return PyObject_TypeCheck (obj, &value_object_type);
  1323. }

  1324. int
  1325. gdbpy_initialize_values (void)
  1326. {
  1327.   if (PyType_Ready (&value_object_type) < 0)
  1328.     return -1;

  1329.   return gdb_pymodule_addobject (gdb_module, "Value",
  1330.                                  (PyObject *) &value_object_type);
  1331. }



  1332. static PyGetSetDef value_object_getset[] = {
  1333.   { "address", valpy_get_address, NULL, "The address of the value.",
  1334.     NULL },
  1335.   { "is_optimized_out", valpy_get_is_optimized_out, NULL,
  1336.     "Boolean telling whether the value is optimized "
  1337.     "out (i.e., not available).",
  1338.     NULL },
  1339.   { "type", valpy_get_type, NULL, "Type of the value.", NULL },
  1340.   { "dynamic_type", valpy_get_dynamic_type, NULL,
  1341.     "Dynamic type of the value.", NULL },
  1342.   { "is_lazy", valpy_get_is_lazy, NULL,
  1343.     "Boolean telling whether the value is lazy (not fetched yet\n\
  1344. from the inferior).  A lazy value is fetched when needed, or when\n\
  1345. the \"fetch_lazy()\" method is called.", NULL },
  1346.   {NULL/* Sentinel */
  1347. };

  1348. static PyMethodDef value_object_methods[] = {
  1349.   { "cast", valpy_cast, METH_VARARGS, "Cast the value to the supplied type." },
  1350.   { "dynamic_cast", valpy_dynamic_cast, METH_VARARGS,
  1351.     "dynamic_cast (gdb.Type) -> gdb.Value\n\
  1352. Cast the value to the supplied type, as if by the C++ dynamic_cast operator."
  1353.   },
  1354.   { "reinterpret_cast", valpy_reinterpret_cast, METH_VARARGS,
  1355.     "reinterpret_cast (gdb.Type) -> gdb.Value\n\
  1356. Cast the value to the supplied type, as if by the C++\n\
  1357. reinterpret_cast operator."
  1358.   },
  1359.   { "dereference", valpy_dereference, METH_NOARGS, "Dereferences the value." },
  1360.   { "referenced_value", valpy_referenced_value, METH_NOARGS,
  1361.     "Return the value referenced by a TYPE_CODE_REF or TYPE_CODE_PTR value." },
  1362.   { "lazy_string", (PyCFunction) valpy_lazy_string,
  1363.     METH_VARARGS | METH_KEYWORDS,
  1364.     "lazy_string ([encoding]  [, length]) -> lazy_string\n\
  1365. Return a lazy string representation of the value." },
  1366.   { "string", (PyCFunction) valpy_string, METH_VARARGS | METH_KEYWORDS,
  1367.     "string ([encoding] [, errors] [, length]) -> string\n\
  1368. Return Unicode string representation of the value." },
  1369.   { "fetch_lazy", valpy_fetch_lazy, METH_NOARGS,
  1370.     "Fetches the value from the inferior, if it was lazy." },
  1371.   {NULL/* Sentinel */
  1372. };

  1373. static PyNumberMethods value_object_as_number = {
  1374.   valpy_add,
  1375.   valpy_subtract,
  1376.   valpy_multiply,
  1377. #ifndef IS_PY3K
  1378.   valpy_divide,
  1379. #endif
  1380.   valpy_remainder,
  1381.   NULL,                              /* nb_divmod */
  1382.   valpy_power,                      /* nb_power */
  1383.   valpy_negative,              /* nb_negative */
  1384.   valpy_positive,              /* nb_positive */
  1385.   valpy_absolute,              /* nb_absolute */
  1386.   valpy_nonzero,              /* nb_nonzero */
  1387.   valpy_invert,                      /* nb_invert */
  1388.   valpy_lsh,                      /* nb_lshift */
  1389.   valpy_rsh,                      /* nb_rshift */
  1390.   valpy_and,                      /* nb_and */
  1391.   valpy_xor,                      /* nb_xor */
  1392.   valpy_or,                      /* nb_or */
  1393. #ifdef IS_PY3K
  1394.   valpy_long,                      /* nb_int */
  1395.   NULL,                              /* reserved */
  1396. #else
  1397.   NULL,                              /* nb_coerce */
  1398.   valpy_int,                      /* nb_int */
  1399.   valpy_long,                      /* nb_long */
  1400. #endif
  1401.   valpy_float,                      /* nb_float */
  1402. #ifndef IS_PY3K
  1403.   NULL,                              /* nb_oct */
  1404.   NULL,                       /* nb_hex */
  1405. #endif
  1406.   NULL,                       /* nb_inplace_add */
  1407.   NULL,                       /* nb_inplace_subtract */
  1408.   NULL,                       /* nb_inplace_multiply */
  1409.   NULL,                       /* nb_inplace_remainder */
  1410.   NULL,                       /* nb_inplace_power */
  1411.   NULL,                       /* nb_inplace_lshift */
  1412.   NULL,                       /* nb_inplace_rshift */
  1413.   NULL,                       /* nb_inplace_and */
  1414.   NULL,                       /* nb_inplace_xor */
  1415.   NULL,                       /* nb_inplace_or */
  1416.   NULL,                       /* nb_floor_divide */
  1417.   valpy_divide                /* nb_true_divide */
  1418. };

  1419. static PyMappingMethods value_object_as_mapping = {
  1420.   valpy_length,
  1421.   valpy_getitem,
  1422.   valpy_setitem
  1423. };

  1424. PyTypeObject value_object_type = {
  1425.   PyVarObject_HEAD_INIT (NULL, 0)
  1426.   "gdb.Value",                          /*tp_name*/
  1427.   sizeof (value_object),          /*tp_basicsize*/
  1428.   0,                                  /*tp_itemsize*/
  1429.   valpy_dealloc,                  /*tp_dealloc*/
  1430.   0,                                  /*tp_print*/
  1431.   0,                                  /*tp_getattr*/
  1432.   0,                                  /*tp_setattr*/
  1433.   0,                                  /*tp_compare*/
  1434.   0,                                  /*tp_repr*/
  1435.   &value_object_as_number,          /*tp_as_number*/
  1436.   0,                                  /*tp_as_sequence*/
  1437.   &value_object_as_mapping,          /*tp_as_mapping*/
  1438.   valpy_hash,                          /*tp_hash*/
  1439.   valpy_call,                          /*tp_call*/
  1440.   valpy_str,                          /*tp_str*/
  1441.   0,                                  /*tp_getattro*/
  1442.   0,                                  /*tp_setattro*/
  1443.   0,                                  /*tp_as_buffer*/
  1444.   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES
  1445.   | Py_TPFLAGS_BASETYPE,          /*tp_flags*/
  1446.   "GDB value object",                  /* tp_doc */
  1447.   0,                                  /* tp_traverse */
  1448.   0,                                  /* tp_clear */
  1449.   valpy_richcompare,                  /* tp_richcompare */
  1450.   0,                                  /* tp_weaklistoffset */
  1451.   0,                                  /* tp_iter */
  1452.   0,                                  /* tp_iternext */
  1453.   value_object_methods,                  /* tp_methods */
  1454.   0,                                  /* tp_members */
  1455.   value_object_getset,                  /* tp_getset */
  1456.   0,                                  /* tp_base */
  1457.   0,                                  /* tp_dict */
  1458.   0,                                  /* tp_descr_get */
  1459.   0,                                  /* tp_descr_set */
  1460.   0,                                  /* tp_dictoffset */
  1461.   0,                                  /* tp_init */
  1462.   0,                                  /* tp_alloc */
  1463.   valpy_new                          /* tp_new */
  1464. };