eb3d307b19bf1e0bd7713e600175cb093dbe795c
[external/binutils.git] / gdb / python / py-value.c
1 /* Python interface to values.
2
3    Copyright (C) 2008-2017 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
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.
11
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.
16
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/>.  */
19
20 #include "defs.h"
21 #include "charset.h"
22 #include "value.h"
23 #include "language.h"
24 #include "dfp.h"
25 #include "valprint.h"
26 #include "infcall.h"
27 #include "expression.h"
28 #include "cp-abi.h"
29 #include "python.h"
30
31 #include "python-internal.h"
32 #include "py-ref.h"
33
34 /* Even though Python scalar types directly map to host types, we use
35    target types here to remain consistent with the values system in
36    GDB (which uses target arithmetic).  */
37
38 /* Python's integer type corresponds to C's long type.  */
39 #define builtin_type_pyint builtin_type (python_gdbarch)->builtin_long
40
41 /* Python's float type corresponds to C's double type.  */
42 #define builtin_type_pyfloat builtin_type (python_gdbarch)->builtin_double
43
44 /* Python's long type corresponds to C's long long type.  */
45 #define builtin_type_pylong builtin_type (python_gdbarch)->builtin_long_long
46
47 /* Python's long type corresponds to C's long long type.  Unsigned version.  */
48 #define builtin_type_upylong builtin_type \
49   (python_gdbarch)->builtin_unsigned_long_long
50
51 #define builtin_type_pybool \
52   language_bool_type (python_language, python_gdbarch)
53
54 #define builtin_type_pychar \
55   language_string_char_type (python_language, python_gdbarch)
56
57 typedef struct value_object {
58   PyObject_HEAD
59   struct value_object *next;
60   struct value_object *prev;
61   struct value *value;
62   PyObject *address;
63   PyObject *type;
64   PyObject *dynamic_type;
65 } value_object;
66
67 /* List of all values which are currently exposed to Python. It is
68    maintained so that when an objfile is discarded, preserve_values
69    can copy the values' types if needed.  */
70 /* This variable is unnecessarily initialized to NULL in order to
71    work around a linker bug on MacOS.  */
72 static value_object *values_in_python = NULL;
73
74 /* Called by the Python interpreter when deallocating a value object.  */
75 static void
76 valpy_dealloc (PyObject *obj)
77 {
78   value_object *self = (value_object *) obj;
79
80   /* Remove SELF from the global list.  */
81   if (self->prev)
82     self->prev->next = self->next;
83   else
84     {
85       gdb_assert (values_in_python == self);
86       values_in_python = self->next;
87     }
88   if (self->next)
89     self->next->prev = self->prev;
90
91   value_free (self->value);
92
93   if (self->address)
94     /* Use braces to appease gcc warning.  *sigh*  */
95     {
96       Py_DECREF (self->address);
97     }
98
99   if (self->type)
100     {
101       Py_DECREF (self->type);
102     }
103
104   Py_XDECREF (self->dynamic_type);
105
106   Py_TYPE (self)->tp_free (self);
107 }
108
109 /* Helper to push a Value object on the global list.  */
110 static void
111 note_value (value_object *value_obj)
112 {
113   value_obj->next = values_in_python;
114   if (value_obj->next)
115     value_obj->next->prev = value_obj;
116   value_obj->prev = NULL;
117   values_in_python = value_obj;
118 }
119
120 /* Called when a new gdb.Value object needs to be allocated.  Returns NULL on
121    error, with a python exception set.  */
122 static PyObject *
123 valpy_new (PyTypeObject *subtype, PyObject *args, PyObject *keywords)
124 {
125   struct value *value = NULL;   /* Initialize to appease gcc warning.  */
126   value_object *value_obj;
127
128   if (PyTuple_Size (args) != 1)
129     {
130       PyErr_SetString (PyExc_TypeError, _("Value object creation takes only "
131                                           "1 argument"));
132       return NULL;
133     }
134
135   value_obj = (value_object *) subtype->tp_alloc (subtype, 1);
136   if (value_obj == NULL)
137     {
138       PyErr_SetString (PyExc_MemoryError, _("Could not allocate memory to "
139                                             "create Value object."));
140       return NULL;
141     }
142
143   value = convert_value_from_python (PyTuple_GetItem (args, 0));
144   if (value == NULL)
145     {
146       subtype->tp_free (value_obj);
147       return NULL;
148     }
149
150   value_obj->value = value;
151   release_value_or_incref (value);
152   value_obj->address = NULL;
153   value_obj->type = NULL;
154   value_obj->dynamic_type = NULL;
155   note_value (value_obj);
156
157   return (PyObject *) value_obj;
158 }
159
160 /* Iterate over all the Value objects, calling preserve_one_value on
161    each.  */
162 void
163 gdbpy_preserve_values (const struct extension_language_defn *extlang,
164                        struct objfile *objfile, htab_t copied_types)
165 {
166   value_object *iter;
167
168   for (iter = values_in_python; iter; iter = iter->next)
169     preserve_one_value (iter->value, objfile, copied_types);
170 }
171
172 /* Given a value of a pointer type, apply the C unary * operator to it.  */
173 static PyObject *
174 valpy_dereference (PyObject *self, PyObject *args)
175 {
176   PyObject *result = NULL;
177
178   TRY
179     {
180       struct value *res_val;
181       scoped_value_mark free_values;
182
183       res_val = value_ind (((value_object *) self)->value);
184       result = value_to_value_object (res_val);
185     }
186   CATCH (except, RETURN_MASK_ALL)
187     {
188       GDB_PY_HANDLE_EXCEPTION (except);
189     }
190   END_CATCH
191
192   return result;
193 }
194
195 /* Given a value of a pointer type or a reference type, return the value
196    referenced. The difference between this function and valpy_dereference is
197    that the latter applies * unary operator to a value, which need not always
198    result in the value referenced. For example, for a value which is a reference
199    to an 'int' pointer ('int *'), valpy_dereference will result in a value of
200    type 'int' while valpy_referenced_value will result in a value of type
201    'int *'.  */
202
203 static PyObject *
204 valpy_referenced_value (PyObject *self, PyObject *args)
205 {
206   PyObject *result = NULL;
207
208   TRY
209     {
210       struct value *self_val, *res_val;
211       scoped_value_mark free_values;
212
213       self_val = ((value_object *) self)->value;
214       switch (TYPE_CODE (check_typedef (value_type (self_val))))
215         {
216         case TYPE_CODE_PTR:
217           res_val = value_ind (self_val);
218           break;
219         case TYPE_CODE_REF:
220           res_val = coerce_ref (self_val);
221           break;
222         default:
223           error(_("Trying to get the referenced value from a value which is "
224                   "neither a pointer nor a reference."));
225         }
226
227       result = value_to_value_object (res_val);
228     }
229   CATCH (except, RETURN_MASK_ALL)
230     {
231       GDB_PY_HANDLE_EXCEPTION (except);
232     }
233   END_CATCH
234
235   return result;
236 }
237
238 /* Return a value which is a reference to the value.  */
239
240 static PyObject *
241 valpy_reference_value (PyObject *self, PyObject *args)
242 {
243   PyObject *result = NULL;
244
245   TRY
246     {
247       struct value *self_val;
248       scoped_value_mark free_values;
249
250       self_val = ((value_object *) self)->value;
251       result = value_to_value_object (value_ref (self_val));
252     }
253   CATCH (except, RETURN_MASK_ALL)
254     {
255       GDB_PY_HANDLE_EXCEPTION (except);
256     }
257   END_CATCH
258
259   return result;
260 }
261
262 /* Return a "const" qualified version of the value.  */
263
264 static PyObject *
265 valpy_const_value (PyObject *self, PyObject *args)
266 {
267   PyObject *result = NULL;
268
269   TRY
270     {
271       struct value *self_val, *res_val;
272       scoped_value_mark free_values;
273
274       self_val = ((value_object *) self)->value;
275       res_val = make_cv_value (1, 0, self_val);
276       result = value_to_value_object (res_val);
277     }
278   CATCH (except, RETURN_MASK_ALL)
279     {
280       GDB_PY_HANDLE_EXCEPTION (except);
281     }
282   END_CATCH
283
284   return result;
285 }
286
287 /* Return "&value".  */
288 static PyObject *
289 valpy_get_address (PyObject *self, void *closure)
290 {
291   value_object *val_obj = (value_object *) self;
292
293   if (!val_obj->address)
294     {
295       TRY
296         {
297           struct value *res_val;
298           scoped_value_mark free_values;
299
300           res_val = value_addr (val_obj->value);
301           val_obj->address = value_to_value_object (res_val);
302         }
303       CATCH (except, RETURN_MASK_ALL)
304         {
305           val_obj->address = Py_None;
306           Py_INCREF (Py_None);
307         }
308       END_CATCH
309     }
310
311   Py_XINCREF (val_obj->address);
312
313   return val_obj->address;
314 }
315
316 /* Return type of the value.  */
317 static PyObject *
318 valpy_get_type (PyObject *self, void *closure)
319 {
320   value_object *obj = (value_object *) self;
321
322   if (!obj->type)
323     {
324       obj->type = type_to_type_object (value_type (obj->value));
325       if (!obj->type)
326         return NULL;
327     }
328   Py_INCREF (obj->type);
329   return obj->type;
330 }
331
332 /* Return dynamic type of the value.  */
333
334 static PyObject *
335 valpy_get_dynamic_type (PyObject *self, void *closure)
336 {
337   value_object *obj = (value_object *) self;
338   struct type *type = NULL;
339
340   if (obj->dynamic_type != NULL)
341     {
342       Py_INCREF (obj->dynamic_type);
343       return obj->dynamic_type;
344     }
345
346   TRY
347     {
348       struct value *val = obj->value;
349       scoped_value_mark free_values;
350
351       type = value_type (val);
352       type = check_typedef (type);
353
354       if (((TYPE_CODE (type) == TYPE_CODE_PTR)
355            || (TYPE_CODE (type) == TYPE_CODE_REF))
356           && (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_STRUCT))
357         {
358           struct value *target;
359           int was_pointer = TYPE_CODE (type) == TYPE_CODE_PTR;
360
361           if (was_pointer)
362             target = value_ind (val);
363           else
364             target = coerce_ref (val);
365           type = value_rtti_type (target, NULL, NULL, NULL);
366
367           if (type)
368             {
369               if (was_pointer)
370                 type = lookup_pointer_type (type);
371               else
372                 type = lookup_reference_type (type);
373             }
374         }
375       else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
376         type = value_rtti_type (val, NULL, NULL, NULL);
377       else
378         {
379           /* Re-use object's static type.  */
380           type = NULL;
381         }
382     }
383   CATCH (except, RETURN_MASK_ALL)
384     {
385       GDB_PY_HANDLE_EXCEPTION (except);
386     }
387   END_CATCH
388
389   if (type == NULL)
390     obj->dynamic_type = valpy_get_type (self, NULL);
391   else
392     obj->dynamic_type = type_to_type_object (type);
393
394   Py_XINCREF (obj->dynamic_type);
395   return obj->dynamic_type;
396 }
397
398 /* Implementation of gdb.Value.lazy_string ([encoding] [, length]) ->
399    string.  Return a PyObject representing a lazy_string_object type.
400    A lazy string is a pointer to a string with an optional encoding and
401    length.  If ENCODING is not given, encoding is set to None.  If an
402    ENCODING is provided the encoding parameter is set to ENCODING, but
403    the string is not encoded.  If LENGTH is provided then the length
404    parameter is set to LENGTH, otherwise length will be set to -1 (first
405    null of appropriate with).  */
406 static PyObject *
407 valpy_lazy_string (PyObject *self, PyObject *args, PyObject *kw)
408 {
409   gdb_py_longest length = -1;
410   struct value *value = ((value_object *) self)->value;
411   const char *user_encoding = NULL;
412   static char *keywords[] = { "encoding", "length", NULL };
413   PyObject *str_obj = NULL;
414
415   if (!PyArg_ParseTupleAndKeywords (args, kw, "|s" GDB_PY_LL_ARG, keywords,
416                                     &user_encoding, &length))
417     return NULL;
418
419   TRY
420     {
421       scoped_value_mark free_values;
422
423       if (TYPE_CODE (value_type (value)) == TYPE_CODE_PTR)
424         value = value_ind (value);
425
426       str_obj = gdbpy_create_lazy_string_object (value_address (value), length,
427                                                  user_encoding,
428                                                  value_type (value));
429     }
430   CATCH (except, RETURN_MASK_ALL)
431     {
432       GDB_PY_HANDLE_EXCEPTION (except);
433     }
434   END_CATCH
435
436   return str_obj;
437 }
438
439 /* Implementation of gdb.Value.string ([encoding] [, errors]
440    [, length]) -> string.  Return Unicode string with value contents.
441    If ENCODING is not given, the string is assumed to be encoded in
442    the target's charset.  If LENGTH is provided, only fetch string to
443    the length provided.  */
444
445 static PyObject *
446 valpy_string (PyObject *self, PyObject *args, PyObject *kw)
447 {
448   int length = -1;
449   gdb_byte *buffer;
450   struct value *value = ((value_object *) self)->value;
451   PyObject *unicode;
452   const char *encoding = NULL;
453   const char *errors = NULL;
454   const char *user_encoding = NULL;
455   const char *la_encoding = NULL;
456   struct type *char_type;
457   static char *keywords[] = { "encoding", "errors", "length", NULL };
458
459   if (!PyArg_ParseTupleAndKeywords (args, kw, "|ssi", keywords,
460                                     &user_encoding, &errors, &length))
461     return NULL;
462
463   TRY
464     {
465       LA_GET_STRING (value, &buffer, &length, &char_type, &la_encoding);
466     }
467   CATCH (except, RETURN_MASK_ALL)
468     {
469       GDB_PY_HANDLE_EXCEPTION (except);
470     }
471   END_CATCH
472
473   encoding = (user_encoding && *user_encoding) ? user_encoding : la_encoding;
474   unicode = PyUnicode_Decode ((const char *) buffer,
475                               length * TYPE_LENGTH (char_type),
476                               encoding, errors);
477   xfree (buffer);
478
479   return unicode;
480 }
481
482 /* A helper function that implements the various cast operators.  */
483
484 static PyObject *
485 valpy_do_cast (PyObject *self, PyObject *args, enum exp_opcode op)
486 {
487   PyObject *type_obj, *result = NULL;
488   struct type *type;
489
490   if (! PyArg_ParseTuple (args, "O", &type_obj))
491     return NULL;
492
493   type = type_object_to_type (type_obj);
494   if (! type)
495     {
496       PyErr_SetString (PyExc_RuntimeError,
497                        _("Argument must be a type."));
498       return NULL;
499     }
500
501   TRY
502     {
503       struct value *val = ((value_object *) self)->value;
504       struct value *res_val;
505       scoped_value_mark free_values;
506
507       if (op == UNOP_DYNAMIC_CAST)
508         res_val = value_dynamic_cast (type, val);
509       else if (op == UNOP_REINTERPRET_CAST)
510         res_val = value_reinterpret_cast (type, val);
511       else
512         {
513           gdb_assert (op == UNOP_CAST);
514           res_val = value_cast (type, val);
515         }
516
517       result = value_to_value_object (res_val);
518     }
519   CATCH (except, RETURN_MASK_ALL)
520     {
521       GDB_PY_HANDLE_EXCEPTION (except);
522     }
523   END_CATCH
524
525   return result;
526 }
527
528 /* Implementation of the "cast" method.  */
529
530 static PyObject *
531 valpy_cast (PyObject *self, PyObject *args)
532 {
533   return valpy_do_cast (self, args, UNOP_CAST);
534 }
535
536 /* Implementation of the "dynamic_cast" method.  */
537
538 static PyObject *
539 valpy_dynamic_cast (PyObject *self, PyObject *args)
540 {
541   return valpy_do_cast (self, args, UNOP_DYNAMIC_CAST);
542 }
543
544 /* Implementation of the "reinterpret_cast" method.  */
545
546 static PyObject *
547 valpy_reinterpret_cast (PyObject *self, PyObject *args)
548 {
549   return valpy_do_cast (self, args, UNOP_REINTERPRET_CAST);
550 }
551
552 static Py_ssize_t
553 valpy_length (PyObject *self)
554 {
555   /* We don't support getting the number of elements in a struct / class.  */
556   PyErr_SetString (PyExc_NotImplementedError,
557                    _("Invalid operation on gdb.Value."));
558   return -1;
559 }
560
561 /* Return 1 if the gdb.Field object FIELD is present in the value V.
562    Returns 0 otherwise.  If any Python error occurs, -1 is returned.  */
563
564 static int
565 value_has_field (struct value *v, PyObject *field)
566 {
567   struct type *parent_type, *val_type;
568   enum type_code type_code;
569   gdbpy_ref<> type_object (PyObject_GetAttrString (field, "parent_type"));
570   int has_field = 0;
571
572   if (type_object == NULL)
573     return -1;
574
575   parent_type = type_object_to_type (type_object.get ());
576   if (parent_type == NULL)
577     {
578       PyErr_SetString (PyExc_TypeError,
579                        _("'parent_type' attribute of gdb.Field object is not a"
580                          "gdb.Type object."));
581       return -1;
582     }
583
584   TRY
585     {
586       val_type = value_type (v);
587       val_type = check_typedef (val_type);
588       if (TYPE_CODE (val_type) == TYPE_CODE_REF
589           || TYPE_CODE (val_type) == TYPE_CODE_PTR)
590       val_type = check_typedef (TYPE_TARGET_TYPE (val_type));
591
592       type_code = TYPE_CODE (val_type);
593       if ((type_code == TYPE_CODE_STRUCT || type_code == TYPE_CODE_UNION)
594           && types_equal (val_type, parent_type))
595         has_field = 1;
596       else
597         has_field = 0;
598     }
599   CATCH (except, RETURN_MASK_ALL)
600     {
601       GDB_PY_SET_HANDLE_EXCEPTION (except);
602     }
603   END_CATCH
604
605   return has_field;
606 }
607
608 /* Return the value of a flag FLAG_NAME in a gdb.Field object FIELD.
609    Returns 1 if the flag value is true, 0 if it is false, and -1 if
610    a Python error occurs.  */
611
612 static int
613 get_field_flag (PyObject *field, const char *flag_name)
614 {
615   gdbpy_ref<> flag_object (PyObject_GetAttrString (field, flag_name));
616
617   if (flag_object == NULL)
618     return -1;
619
620   return PyObject_IsTrue (flag_object.get ());
621 }
622
623 /* Return the "type" attribute of a gdb.Field object.
624    Returns NULL on error, with a Python exception set.  */
625
626 static struct type *
627 get_field_type (PyObject *field)
628 {
629   gdbpy_ref<> ftype_obj (PyObject_GetAttrString (field, "type"));
630   struct type *ftype;
631
632   if (ftype_obj == NULL)
633     return NULL;
634   ftype = type_object_to_type (ftype_obj.get ());
635   if (ftype == NULL)
636     PyErr_SetString (PyExc_TypeError,
637                      _("'type' attribute of gdb.Field object is not a "
638                        "gdb.Type object."));
639
640   return ftype;
641 }
642
643 /* Given string name or a gdb.Field object corresponding to an element inside
644    a structure, return its value object.  Returns NULL on error, with a python
645    exception set.  */
646
647 static PyObject *
648 valpy_getitem (PyObject *self, PyObject *key)
649 {
650   struct gdb_exception except = exception_none;
651   value_object *self_value = (value_object *) self;
652   gdb::unique_xmalloc_ptr<char> field;
653   struct type *base_class_type = NULL, *field_type = NULL;
654   long bitpos = -1;
655   PyObject *result = NULL;
656
657   if (gdbpy_is_string (key))
658     {
659       field = python_string_to_host_string (key);
660       if (field == NULL)
661         return NULL;
662     }
663   else if (gdbpy_is_field (key))
664     {
665       int is_base_class, valid_field;
666
667       valid_field = value_has_field (self_value->value, key);
668       if (valid_field < 0)
669         return NULL;
670       else if (valid_field == 0)
671         {
672           PyErr_SetString (PyExc_TypeError,
673                            _("Invalid lookup for a field not contained in "
674                              "the value."));
675
676           return NULL;
677         }
678
679       is_base_class = get_field_flag (key, "is_base_class");
680       if (is_base_class < 0)
681         return NULL;
682       else if (is_base_class > 0)
683         {
684           base_class_type = get_field_type (key);
685           if (base_class_type == NULL)
686             return NULL;
687         }
688       else
689         {
690           gdbpy_ref<> name_obj (PyObject_GetAttrString (key, "name"));
691
692           if (name_obj == NULL)
693             return NULL;
694
695           if (name_obj != Py_None)
696             {
697               field = python_string_to_host_string (name_obj.get ());
698               if (field == NULL)
699                 return NULL;
700             }
701           else
702             {
703               if (!PyObject_HasAttrString (key, "bitpos"))
704                 {
705                   PyErr_SetString (PyExc_AttributeError,
706                                    _("gdb.Field object has no name and no "
707                                      "'bitpos' attribute."));
708
709                   return NULL;
710                 }
711               gdbpy_ref<> bitpos_obj (PyObject_GetAttrString (key, "bitpos"));
712               if (bitpos_obj == NULL)
713                 return NULL;
714               if (!gdb_py_int_as_long (bitpos_obj.get (), &bitpos))
715                 return NULL;
716
717               field_type = get_field_type (key);
718               if (field_type == NULL)
719                 return NULL;
720             }
721         }
722     }
723
724   TRY
725     {
726       struct value *tmp = self_value->value;
727       struct value *res_val = NULL;
728       scoped_value_mark free_values;
729
730       if (field)
731         res_val = value_struct_elt (&tmp, NULL, field.get (), NULL,
732                                     "struct/class/union");
733       else if (bitpos >= 0)
734         res_val = value_struct_elt_bitpos (&tmp, bitpos, field_type,
735                                            "struct/class/union");
736       else if (base_class_type != NULL)
737         {
738           struct type *val_type;
739
740           val_type = check_typedef (value_type (tmp));
741           if (TYPE_CODE (val_type) == TYPE_CODE_PTR)
742             res_val = value_cast (lookup_pointer_type (base_class_type), tmp);
743           else if (TYPE_CODE (val_type) == TYPE_CODE_REF)
744             res_val = value_cast (lookup_reference_type (base_class_type), tmp);
745           else
746             res_val = value_cast (base_class_type, tmp);
747         }
748       else
749         {
750           /* Assume we are attempting an array access, and let the
751              value code throw an exception if the index has an invalid
752              type.  */
753           struct value *idx = convert_value_from_python (key);
754
755           if (idx != NULL)
756             {
757               /* Check the value's type is something that can be accessed via
758                  a subscript.  */
759               struct type *type;
760
761               tmp = coerce_ref (tmp);
762               type = check_typedef (value_type (tmp));
763               if (TYPE_CODE (type) != TYPE_CODE_ARRAY
764                   && TYPE_CODE (type) != TYPE_CODE_PTR)
765                   error (_("Cannot subscript requested type."));
766               else
767                 res_val = value_subscript (tmp, value_as_long (idx));
768             }
769         }
770
771       if (res_val)
772         result = value_to_value_object (res_val);
773     }
774   CATCH (ex, RETURN_MASK_ALL)
775     {
776       except = ex;
777     }
778   END_CATCH
779
780   GDB_PY_HANDLE_EXCEPTION (except);
781
782   return result;
783 }
784
785 static int
786 valpy_setitem (PyObject *self, PyObject *key, PyObject *value)
787 {
788   PyErr_Format (PyExc_NotImplementedError,
789                 _("Setting of struct elements is not currently supported."));
790   return -1;
791 }
792
793 /* Called by the Python interpreter to perform an inferior function
794    call on the value.  Returns NULL on error, with a python exception set.  */
795 static PyObject *
796 valpy_call (PyObject *self, PyObject *args, PyObject *keywords)
797 {
798   Py_ssize_t args_count;
799   struct value *function = ((value_object *) self)->value;
800   struct value **vargs = NULL;
801   struct type *ftype = NULL;
802   struct value *mark = value_mark ();
803   PyObject *result = NULL;
804
805   TRY
806     {
807       ftype = check_typedef (value_type (function));
808     }
809   CATCH (except, RETURN_MASK_ALL)
810     {
811       GDB_PY_HANDLE_EXCEPTION (except);
812     }
813   END_CATCH
814
815   if (TYPE_CODE (ftype) != TYPE_CODE_FUNC)
816     {
817       PyErr_SetString (PyExc_RuntimeError,
818                        _("Value is not callable (not TYPE_CODE_FUNC)."));
819       return NULL;
820     }
821
822   if (! PyTuple_Check (args))
823     {
824       PyErr_SetString (PyExc_TypeError,
825                        _("Inferior arguments must be provided in a tuple."));
826       return NULL;
827     }
828
829   args_count = PyTuple_Size (args);
830   if (args_count > 0)
831     {
832       int i;
833
834       vargs = XALLOCAVEC (struct value *, args_count);
835       for (i = 0; i < args_count; i++)
836         {
837           PyObject *item = PyTuple_GetItem (args, i);
838
839           if (item == NULL)
840             return NULL;
841
842           vargs[i] = convert_value_from_python (item);
843           if (vargs[i] == NULL)
844             return NULL;
845         }
846     }
847
848   TRY
849     {
850       scoped_value_mark free_values;
851       struct value *return_value;
852
853       return_value = call_function_by_hand (function, args_count, vargs);
854       result = value_to_value_object (return_value);
855     }
856   CATCH (except, RETURN_MASK_ALL)
857     {
858       GDB_PY_HANDLE_EXCEPTION (except);
859     }
860   END_CATCH
861
862   return result;
863 }
864
865 /* Called by the Python interpreter to obtain string representation
866    of the object.  */
867 static PyObject *
868 valpy_str (PyObject *self)
869 {
870   struct value_print_options opts;
871
872   get_user_print_options (&opts);
873   opts.deref_ref = 0;
874
875   string_file stb;
876
877   TRY
878     {
879       common_val_print (((value_object *) self)->value, &stb, 0,
880                         &opts, python_language);
881     }
882   CATCH (except, RETURN_MASK_ALL)
883     {
884       GDB_PY_HANDLE_EXCEPTION (except);
885     }
886   END_CATCH
887
888   return PyUnicode_Decode (stb.c_str (), stb.size (), host_charset (), NULL);
889 }
890
891 /* Implements gdb.Value.is_optimized_out.  */
892 static PyObject *
893 valpy_get_is_optimized_out (PyObject *self, void *closure)
894 {
895   struct value *value = ((value_object *) self)->value;
896   int opt = 0;
897
898   TRY
899     {
900       opt = value_optimized_out (value);
901     }
902   CATCH (except, RETURN_MASK_ALL)
903     {
904       GDB_PY_HANDLE_EXCEPTION (except);
905     }
906   END_CATCH
907
908   if (opt)
909     Py_RETURN_TRUE;
910
911   Py_RETURN_FALSE;
912 }
913
914 /* Implements gdb.Value.is_lazy.  */
915 static PyObject *
916 valpy_get_is_lazy (PyObject *self, void *closure)
917 {
918   struct value *value = ((value_object *) self)->value;
919   int opt = 0;
920
921   TRY
922     {
923       opt = value_lazy (value);
924     }
925   CATCH (except, RETURN_MASK_ALL)
926     {
927       GDB_PY_HANDLE_EXCEPTION (except);
928     }
929   END_CATCH
930
931   if (opt)
932     Py_RETURN_TRUE;
933
934   Py_RETURN_FALSE;
935 }
936
937 /* Implements gdb.Value.fetch_lazy ().  */
938 static PyObject *
939 valpy_fetch_lazy (PyObject *self, PyObject *args)
940 {
941   struct value *value = ((value_object *) self)->value;
942
943   TRY
944     {
945       if (value_lazy (value))
946         value_fetch_lazy (value);
947     }
948   CATCH (except, RETURN_MASK_ALL)
949     {
950       GDB_PY_HANDLE_EXCEPTION (except);
951     }
952   END_CATCH
953
954   Py_RETURN_NONE;
955 }
956
957 /* Calculate and return the address of the PyObject as the value of
958    the builtin __hash__ call.  */
959 static Py_hash_t
960 valpy_hash (PyObject *self)
961 {
962   return (intptr_t) self;
963 }
964
965 enum valpy_opcode
966 {
967   VALPY_ADD,
968   VALPY_SUB,
969   VALPY_MUL,
970   VALPY_DIV,
971   VALPY_REM,
972   VALPY_POW,
973   VALPY_LSH,
974   VALPY_RSH,
975   VALPY_BITAND,
976   VALPY_BITOR,
977   VALPY_BITXOR
978 };
979
980 /* If TYPE is a reference, return the target; otherwise return TYPE.  */
981 #define STRIP_REFERENCE(TYPE) \
982   ((TYPE_CODE (TYPE) == TYPE_CODE_REF) ? (TYPE_TARGET_TYPE (TYPE)) : (TYPE))
983
984 /* Helper for valpy_binop.  Returns a value object which is the result
985    of applying the operation specified by OPCODE to the given
986    arguments.  Throws a GDB exception on error.  */
987
988 static PyObject *
989 valpy_binop_throw (enum valpy_opcode opcode, PyObject *self, PyObject *other)
990 {
991   PyObject *result = NULL;
992
993   struct value *arg1, *arg2;
994   struct value *res_val = NULL;
995   enum exp_opcode op = OP_NULL;
996   int handled = 0;
997
998   scoped_value_mark free_values;
999
1000   /* If the gdb.Value object is the second operand, then it will be
1001      passed to us as the OTHER argument, and SELF will be an entirely
1002      different kind of object, altogether.  Because of this, we can't
1003      assume self is a gdb.Value object and need to convert it from
1004      python as well.  */
1005   arg1 = convert_value_from_python (self);
1006   if (arg1 == NULL)
1007     return NULL;
1008
1009   arg2 = convert_value_from_python (other);
1010   if (arg2 == NULL)
1011     return NULL;
1012
1013   switch (opcode)
1014     {
1015     case VALPY_ADD:
1016       {
1017         struct type *ltype = value_type (arg1);
1018         struct type *rtype = value_type (arg2);
1019
1020         ltype = check_typedef (ltype);
1021         ltype = STRIP_REFERENCE (ltype);
1022         rtype = check_typedef (rtype);
1023         rtype = STRIP_REFERENCE (rtype);
1024
1025         handled = 1;
1026         if (TYPE_CODE (ltype) == TYPE_CODE_PTR
1027             && is_integral_type (rtype))
1028           res_val = value_ptradd (arg1, value_as_long (arg2));
1029         else if (TYPE_CODE (rtype) == TYPE_CODE_PTR
1030                  && is_integral_type (ltype))
1031           res_val = value_ptradd (arg2, value_as_long (arg1));
1032         else
1033           {
1034             handled = 0;
1035             op = BINOP_ADD;
1036           }
1037       }
1038       break;
1039     case VALPY_SUB:
1040       {
1041         struct type *ltype = value_type (arg1);
1042         struct type *rtype = value_type (arg2);
1043
1044         ltype = check_typedef (ltype);
1045         ltype = STRIP_REFERENCE (ltype);
1046         rtype = check_typedef (rtype);
1047         rtype = STRIP_REFERENCE (rtype);
1048
1049         handled = 1;
1050         if (TYPE_CODE (ltype) == TYPE_CODE_PTR
1051             && TYPE_CODE (rtype) == TYPE_CODE_PTR)
1052           /* A ptrdiff_t for the target would be preferable here.  */
1053           res_val = value_from_longest (builtin_type_pyint,
1054                                         value_ptrdiff (arg1, arg2));
1055         else if (TYPE_CODE (ltype) == TYPE_CODE_PTR
1056                  && is_integral_type (rtype))
1057           res_val = value_ptradd (arg1, - value_as_long (arg2));
1058         else
1059           {
1060             handled = 0;
1061             op = BINOP_SUB;
1062           }
1063       }
1064       break;
1065     case VALPY_MUL:
1066       op = BINOP_MUL;
1067       break;
1068     case VALPY_DIV:
1069       op = BINOP_DIV;
1070       break;
1071     case VALPY_REM:
1072       op = BINOP_REM;
1073       break;
1074     case VALPY_POW:
1075       op = BINOP_EXP;
1076       break;
1077     case VALPY_LSH:
1078       op = BINOP_LSH;
1079       break;
1080     case VALPY_RSH:
1081       op = BINOP_RSH;
1082       break;
1083     case VALPY_BITAND:
1084       op = BINOP_BITWISE_AND;
1085       break;
1086     case VALPY_BITOR:
1087       op = BINOP_BITWISE_IOR;
1088       break;
1089     case VALPY_BITXOR:
1090       op = BINOP_BITWISE_XOR;
1091       break;
1092     }
1093
1094   if (!handled)
1095     {
1096       if (binop_user_defined_p (op, arg1, arg2))
1097         res_val = value_x_binop (arg1, arg2, op, OP_NULL, EVAL_NORMAL);
1098       else
1099         res_val = value_binop (arg1, arg2, op);
1100     }
1101
1102   if (res_val)
1103     result = value_to_value_object (res_val);
1104
1105   return result;
1106 }
1107
1108 /* Returns a value object which is the result of applying the operation
1109    specified by OPCODE to the given arguments.  Returns NULL on error, with
1110    a python exception set.  */
1111 static PyObject *
1112 valpy_binop (enum valpy_opcode opcode, PyObject *self, PyObject *other)
1113 {
1114   PyObject *result = NULL;
1115
1116   TRY
1117     {
1118       result = valpy_binop_throw (opcode, self, other);
1119     }
1120   CATCH (except, RETURN_MASK_ALL)
1121     {
1122       GDB_PY_HANDLE_EXCEPTION (except);
1123     }
1124   END_CATCH
1125
1126   return result;
1127 }
1128
1129 static PyObject *
1130 valpy_add (PyObject *self, PyObject *other)
1131 {
1132   return valpy_binop (VALPY_ADD, self, other);
1133 }
1134
1135 static PyObject *
1136 valpy_subtract (PyObject *self, PyObject *other)
1137 {
1138   return valpy_binop (VALPY_SUB, self, other);
1139 }
1140
1141 static PyObject *
1142 valpy_multiply (PyObject *self, PyObject *other)
1143 {
1144   return valpy_binop (VALPY_MUL, self, other);
1145 }
1146
1147 static PyObject *
1148 valpy_divide (PyObject *self, PyObject *other)
1149 {
1150   return valpy_binop (VALPY_DIV, self, other);
1151 }
1152
1153 static PyObject *
1154 valpy_remainder (PyObject *self, PyObject *other)
1155 {
1156   return valpy_binop (VALPY_REM, self, other);
1157 }
1158
1159 static PyObject *
1160 valpy_power (PyObject *self, PyObject *other, PyObject *unused)
1161 {
1162   /* We don't support the ternary form of pow.  I don't know how to express
1163      that, so let's just throw NotImplementedError to at least do something
1164      about it.  */
1165   if (unused != Py_None)
1166     {
1167       PyErr_SetString (PyExc_NotImplementedError,
1168                        "Invalid operation on gdb.Value.");
1169       return NULL;
1170     }
1171
1172   return valpy_binop (VALPY_POW, self, other);
1173 }
1174
1175 static PyObject *
1176 valpy_negative (PyObject *self)
1177 {
1178   PyObject *result = NULL;
1179
1180   TRY
1181     {
1182       /* Perhaps overkill, but consistency has some virtue.  */
1183       scoped_value_mark free_values;
1184       struct value *val;
1185
1186       val = value_neg (((value_object *) self)->value);
1187       result = value_to_value_object (val);
1188     }
1189   CATCH (except, RETURN_MASK_ALL)
1190     {
1191       GDB_PY_HANDLE_EXCEPTION (except);
1192     }
1193   END_CATCH
1194
1195   return result;
1196 }
1197
1198 static PyObject *
1199 valpy_positive (PyObject *self)
1200 {
1201   return value_to_value_object (((value_object *) self)->value);
1202 }
1203
1204 static PyObject *
1205 valpy_absolute (PyObject *self)
1206 {
1207   struct value *value = ((value_object *) self)->value;
1208   int isabs = 1;
1209
1210   TRY
1211     {
1212       scoped_value_mark free_values;
1213
1214       if (value_less (value, value_zero (value_type (value), not_lval)))
1215         isabs = 0;
1216     }
1217   CATCH (except, RETURN_MASK_ALL)
1218     {
1219       GDB_PY_HANDLE_EXCEPTION (except);
1220     }
1221   END_CATCH
1222
1223   if (isabs)
1224     return valpy_positive (self);
1225   else
1226     return valpy_negative (self);
1227 }
1228
1229 /* Implements boolean evaluation of gdb.Value.  */
1230 static int
1231 valpy_nonzero (PyObject *self)
1232 {
1233   struct gdb_exception except = exception_none;
1234   value_object *self_value = (value_object *) self;
1235   struct type *type;
1236   int nonzero = 0; /* Appease GCC warning.  */
1237
1238   TRY
1239     {
1240       type = check_typedef (value_type (self_value->value));
1241
1242       if (is_integral_type (type) || TYPE_CODE (type) == TYPE_CODE_PTR)
1243         nonzero = !!value_as_long (self_value->value);
1244       else if (TYPE_CODE (type) == TYPE_CODE_FLT)
1245         nonzero = value_as_double (self_value->value) != 0;
1246       else if (TYPE_CODE (type) == TYPE_CODE_DECFLOAT)
1247         nonzero = !decimal_is_zero (value_contents (self_value->value),
1248                                  TYPE_LENGTH (type),
1249                                  gdbarch_byte_order (get_type_arch (type)));
1250       else
1251         /* All other values are True.  */
1252         nonzero = 1;
1253     }
1254   CATCH (ex, RETURN_MASK_ALL)
1255     {
1256       except = ex;
1257     }
1258   END_CATCH
1259
1260   /* This is not documented in the Python documentation, but if this
1261      function fails, return -1 as slot_nb_nonzero does (the default
1262      Python nonzero function).  */
1263   GDB_PY_SET_HANDLE_EXCEPTION (except);
1264
1265   return nonzero;
1266 }
1267
1268 /* Implements ~ for value objects.  */
1269 static PyObject *
1270 valpy_invert (PyObject *self)
1271 {
1272   struct value *val = NULL;
1273
1274   TRY
1275     {
1276       val = value_complement (((value_object *) self)->value);
1277     }
1278   CATCH (except, RETURN_MASK_ALL)
1279     {
1280       GDB_PY_HANDLE_EXCEPTION (except);
1281     }
1282   END_CATCH
1283
1284   return value_to_value_object (val);
1285 }
1286
1287 /* Implements left shift for value objects.  */
1288 static PyObject *
1289 valpy_lsh (PyObject *self, PyObject *other)
1290 {
1291   return valpy_binop (VALPY_LSH, self, other);
1292 }
1293
1294 /* Implements right shift for value objects.  */
1295 static PyObject *
1296 valpy_rsh (PyObject *self, PyObject *other)
1297 {
1298   return valpy_binop (VALPY_RSH, self, other);
1299 }
1300
1301 /* Implements bitwise and for value objects.  */
1302 static PyObject *
1303 valpy_and (PyObject *self, PyObject *other)
1304 {
1305   return valpy_binop (VALPY_BITAND, self, other);
1306 }
1307
1308 /* Implements bitwise or for value objects.  */
1309 static PyObject *
1310 valpy_or (PyObject *self, PyObject *other)
1311 {
1312   return valpy_binop (VALPY_BITOR, self, other);
1313 }
1314
1315 /* Implements bitwise xor for value objects.  */
1316 static PyObject *
1317 valpy_xor (PyObject *self, PyObject *other)
1318 {
1319   return valpy_binop (VALPY_BITXOR, self, other);
1320 }
1321
1322 /* Helper for valpy_richcompare.  Implements comparison operations for
1323    value objects.  Returns true/false on success.  Returns -1 with a
1324    Python exception set if a Python error is detected.  Throws a GDB
1325    exception on other errors (memory error, etc.).  */
1326
1327 static int
1328 valpy_richcompare_throw (PyObject *self, PyObject *other, int op)
1329 {
1330   int result;
1331   struct value *value_other;
1332   struct value *value_self;
1333
1334   scoped_value_mark free_values;
1335
1336   value_other = convert_value_from_python (other);
1337   if (value_other == NULL)
1338     return -1;
1339
1340   value_self = ((value_object *) self)->value;
1341
1342   switch (op)
1343     {
1344     case Py_LT:
1345       result = value_less (value_self, value_other);
1346       break;
1347     case Py_LE:
1348       result = value_less (value_self, value_other)
1349         || value_equal (value_self, value_other);
1350       break;
1351     case Py_EQ:
1352       result = value_equal (value_self, value_other);
1353       break;
1354     case Py_NE:
1355       result = !value_equal (value_self, value_other);
1356       break;
1357     case Py_GT:
1358       result = value_less (value_other, value_self);
1359       break;
1360     case Py_GE:
1361       result = (value_less (value_other, value_self)
1362                 || value_equal (value_self, value_other));
1363       break;
1364     default:
1365       /* Can't happen.  */
1366       PyErr_SetString (PyExc_NotImplementedError,
1367                        _("Invalid operation on gdb.Value."));
1368       result = -1;
1369       break;
1370     }
1371
1372   return result;
1373 }
1374
1375
1376 /* Implements comparison operations for value objects.  Returns NULL on error,
1377    with a python exception set.  */
1378 static PyObject *
1379 valpy_richcompare (PyObject *self, PyObject *other, int op)
1380 {
1381   int result = 0;
1382
1383   if (other == Py_None)
1384     /* Comparing with None is special.  From what I can tell, in Python
1385        None is smaller than anything else.  */
1386     switch (op) {
1387       case Py_LT:
1388       case Py_LE:
1389       case Py_EQ:
1390         Py_RETURN_FALSE;
1391       case Py_NE:
1392       case Py_GT:
1393       case Py_GE:
1394         Py_RETURN_TRUE;
1395       default:
1396         /* Can't happen.  */
1397         PyErr_SetString (PyExc_NotImplementedError,
1398                          _("Invalid operation on gdb.Value."));
1399         return NULL;
1400     }
1401
1402   TRY
1403     {
1404       result = valpy_richcompare_throw (self, other, op);
1405     }
1406   CATCH (except, RETURN_MASK_ALL)
1407     {
1408       GDB_PY_HANDLE_EXCEPTION (except);
1409     }
1410   END_CATCH
1411
1412   /* In this case, the Python exception has already been set.  */
1413   if (result < 0)
1414     return NULL;
1415
1416   if (result == 1)
1417     Py_RETURN_TRUE;
1418
1419   Py_RETURN_FALSE;
1420 }
1421
1422 #ifndef IS_PY3K
1423 /* Implements conversion to int.  */
1424 static PyObject *
1425 valpy_int (PyObject *self)
1426 {
1427   struct value *value = ((value_object *) self)->value;
1428   struct type *type = value_type (value);
1429   LONGEST l = 0;
1430
1431   TRY
1432     {
1433       if (!is_integral_type (type))
1434         error (_("Cannot convert value to int."));
1435
1436       l = value_as_long (value);
1437     }
1438   CATCH (except, RETURN_MASK_ALL)
1439     {
1440       GDB_PY_HANDLE_EXCEPTION (except);
1441     }
1442   END_CATCH
1443
1444   return gdb_py_object_from_longest (l);
1445 }
1446 #endif
1447
1448 /* Implements conversion to long.  */
1449 static PyObject *
1450 valpy_long (PyObject *self)
1451 {
1452   struct value *value = ((value_object *) self)->value;
1453   struct type *type = value_type (value);
1454   LONGEST l = 0;
1455
1456   TRY
1457     {
1458       type = check_typedef (type);
1459
1460       if (!is_integral_type (type)
1461           && TYPE_CODE (type) != TYPE_CODE_PTR)
1462         error (_("Cannot convert value to long."));
1463
1464       l = value_as_long (value);
1465     }
1466   CATCH (except, RETURN_MASK_ALL)
1467     {
1468       GDB_PY_HANDLE_EXCEPTION (except);
1469     }
1470   END_CATCH
1471
1472   if (TYPE_UNSIGNED (type))
1473     return gdb_py_long_from_ulongest (l);
1474   else
1475     return gdb_py_long_from_longest (l);
1476 }
1477
1478 /* Implements conversion to float.  */
1479 static PyObject *
1480 valpy_float (PyObject *self)
1481 {
1482   struct value *value = ((value_object *) self)->value;
1483   struct type *type = value_type (value);
1484   double d = 0;
1485
1486   TRY
1487     {
1488       type = check_typedef (type);
1489
1490       if (TYPE_CODE (type) != TYPE_CODE_FLT)
1491         error (_("Cannot convert value to float."));
1492
1493       d = value_as_double (value);
1494     }
1495   CATCH (except, RETURN_MASK_ALL)
1496     {
1497       GDB_PY_HANDLE_EXCEPTION (except);
1498     }
1499   END_CATCH
1500
1501   return PyFloat_FromDouble (d);
1502 }
1503
1504 /* Returns an object for a value which is released from the all_values chain,
1505    so its lifetime is not bound to the execution of a command.  */
1506 PyObject *
1507 value_to_value_object (struct value *val)
1508 {
1509   value_object *val_obj;
1510
1511   val_obj = PyObject_New (value_object, &value_object_type);
1512   if (val_obj != NULL)
1513     {
1514       val_obj->value = val;
1515       release_value_or_incref (val);
1516       val_obj->address = NULL;
1517       val_obj->type = NULL;
1518       val_obj->dynamic_type = NULL;
1519       note_value (val_obj);
1520     }
1521
1522   return (PyObject *) val_obj;
1523 }
1524
1525 /* Returns a borrowed reference to the struct value corresponding to
1526    the given value object.  */
1527 struct value *
1528 value_object_to_value (PyObject *self)
1529 {
1530   value_object *real;
1531
1532   if (! PyObject_TypeCheck (self, &value_object_type))
1533     return NULL;
1534   real = (value_object *) self;
1535   return real->value;
1536 }
1537
1538 /* Try to convert a Python value to a gdb value.  If the value cannot
1539    be converted, set a Python exception and return NULL.  Returns a
1540    reference to a new value on the all_values chain.  */
1541
1542 struct value *
1543 convert_value_from_python (PyObject *obj)
1544 {
1545   struct value *value = NULL; /* -Wall */
1546   int cmp;
1547
1548   gdb_assert (obj != NULL);
1549
1550   TRY
1551     {
1552       if (PyBool_Check (obj))
1553         {
1554           cmp = PyObject_IsTrue (obj);
1555           if (cmp >= 0)
1556             value = value_from_longest (builtin_type_pybool, cmp);
1557         }
1558       /* Make a long logic check first.  In Python 3.x, internally,
1559          all integers are represented as longs.  In Python 2.x, there
1560          is still a differentiation internally between a PyInt and a
1561          PyLong.  Explicitly do this long check conversion first. In
1562          GDB, for Python 3.x, we #ifdef PyInt = PyLong.  This check has
1563          to be done first to ensure we do not lose information in the
1564          conversion process.  */
1565       else if (PyLong_Check (obj))
1566         {
1567           LONGEST l = PyLong_AsLongLong (obj);
1568
1569           if (PyErr_Occurred ())
1570             {
1571               /* If the error was an overflow, we can try converting to
1572                  ULONGEST instead.  */
1573               if (PyErr_ExceptionMatches (PyExc_OverflowError))
1574                 {
1575                   PyObject *etype, *evalue, *etraceback;
1576
1577                   PyErr_Fetch (&etype, &evalue, &etraceback);
1578                   gdbpy_ref<> zero (PyInt_FromLong (0));
1579
1580                   /* Check whether obj is positive.  */
1581                   if (PyObject_RichCompareBool (obj, zero.get (), Py_GT) > 0)
1582                     {
1583                       ULONGEST ul;
1584
1585                       ul = PyLong_AsUnsignedLongLong (obj);
1586                       if (! PyErr_Occurred ())
1587                         value = value_from_ulongest (builtin_type_upylong, ul);
1588                     }
1589                   else
1590                     /* There's nothing we can do.  */
1591                     PyErr_Restore (etype, evalue, etraceback);
1592                 }
1593             }
1594           else
1595             value = value_from_longest (builtin_type_pylong, l);
1596         }
1597 #if PY_MAJOR_VERSION == 2
1598       else if (PyInt_Check (obj))
1599         {
1600           long l = PyInt_AsLong (obj);
1601
1602           if (! PyErr_Occurred ())
1603             value = value_from_longest (builtin_type_pyint, l);
1604         }
1605 #endif
1606       else if (PyFloat_Check (obj))
1607         {
1608           double d = PyFloat_AsDouble (obj);
1609
1610           if (! PyErr_Occurred ())
1611             value = value_from_double (builtin_type_pyfloat, d);
1612         }
1613       else if (gdbpy_is_string (obj))
1614         {
1615           gdb::unique_xmalloc_ptr<char> s
1616             = python_string_to_target_string (obj);
1617           if (s != NULL)
1618             value = value_cstring (s.get (), strlen (s.get ()),
1619                                    builtin_type_pychar);
1620         }
1621       else if (PyObject_TypeCheck (obj, &value_object_type))
1622         value = value_copy (((value_object *) obj)->value);
1623       else if (gdbpy_is_lazy_string (obj))
1624         {
1625           PyObject *result;
1626
1627           result = PyObject_CallMethodObjArgs (obj, gdbpy_value_cst,  NULL);
1628           value = value_copy (((value_object *) result)->value);
1629         }
1630       else
1631 #ifdef IS_PY3K
1632         PyErr_Format (PyExc_TypeError,
1633                       _("Could not convert Python object: %S."), obj);
1634 #else
1635         PyErr_Format (PyExc_TypeError,
1636                       _("Could not convert Python object: %s."),
1637                       PyString_AsString (PyObject_Str (obj)));
1638 #endif
1639     }
1640   CATCH (except, RETURN_MASK_ALL)
1641     {
1642       PyErr_Format (except.reason == RETURN_QUIT
1643                     ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
1644                     "%s", except.message);
1645       return NULL;
1646     }
1647   END_CATCH
1648
1649   return value;
1650 }
1651
1652 /* Returns value object in the ARGth position in GDB's history.  */
1653 PyObject *
1654 gdbpy_history (PyObject *self, PyObject *args)
1655 {
1656   int i;
1657   struct value *res_val = NULL;   /* Initialize to appease gcc warning.  */
1658
1659   if (!PyArg_ParseTuple (args, "i", &i))
1660     return NULL;
1661
1662   TRY
1663     {
1664       res_val = access_value_history (i);
1665     }
1666   CATCH (except, RETURN_MASK_ALL)
1667     {
1668       GDB_PY_HANDLE_EXCEPTION (except);
1669     }
1670   END_CATCH
1671
1672   return value_to_value_object (res_val);
1673 }
1674
1675 /* Returns 1 in OBJ is a gdb.Value object, 0 otherwise.  */
1676
1677 int
1678 gdbpy_is_value_object (PyObject *obj)
1679 {
1680   return PyObject_TypeCheck (obj, &value_object_type);
1681 }
1682
1683 int
1684 gdbpy_initialize_values (void)
1685 {
1686   if (PyType_Ready (&value_object_type) < 0)
1687     return -1;
1688
1689   return gdb_pymodule_addobject (gdb_module, "Value",
1690                                  (PyObject *) &value_object_type);
1691 }
1692
1693 \f
1694
1695 static PyGetSetDef value_object_getset[] = {
1696   { "address", valpy_get_address, NULL, "The address of the value.",
1697     NULL },
1698   { "is_optimized_out", valpy_get_is_optimized_out, NULL,
1699     "Boolean telling whether the value is optimized "
1700     "out (i.e., not available).",
1701     NULL },
1702   { "type", valpy_get_type, NULL, "Type of the value.", NULL },
1703   { "dynamic_type", valpy_get_dynamic_type, NULL,
1704     "Dynamic type of the value.", NULL },
1705   { "is_lazy", valpy_get_is_lazy, NULL,
1706     "Boolean telling whether the value is lazy (not fetched yet\n\
1707 from the inferior).  A lazy value is fetched when needed, or when\n\
1708 the \"fetch_lazy()\" method is called.", NULL },
1709   {NULL}  /* Sentinel */
1710 };
1711
1712 static PyMethodDef value_object_methods[] = {
1713   { "cast", valpy_cast, METH_VARARGS, "Cast the value to the supplied type." },
1714   { "dynamic_cast", valpy_dynamic_cast, METH_VARARGS,
1715     "dynamic_cast (gdb.Type) -> gdb.Value\n\
1716 Cast the value to the supplied type, as if by the C++ dynamic_cast operator."
1717   },
1718   { "reinterpret_cast", valpy_reinterpret_cast, METH_VARARGS,
1719     "reinterpret_cast (gdb.Type) -> gdb.Value\n\
1720 Cast the value to the supplied type, as if by the C++\n\
1721 reinterpret_cast operator."
1722   },
1723   { "dereference", valpy_dereference, METH_NOARGS, "Dereferences the value." },
1724   { "referenced_value", valpy_referenced_value, METH_NOARGS,
1725     "Return the value referenced by a TYPE_CODE_REF or TYPE_CODE_PTR value." },
1726   { "reference_value", valpy_reference_value, METH_NOARGS,
1727     "Return a value of type TYPE_CODE_REF referencing this value." },
1728   { "const_value", valpy_const_value, METH_NOARGS,
1729     "Return a 'const' qualied version of the same value." },
1730   { "lazy_string", (PyCFunction) valpy_lazy_string,
1731     METH_VARARGS | METH_KEYWORDS,
1732     "lazy_string ([encoding]  [, length]) -> lazy_string\n\
1733 Return a lazy string representation of the value." },
1734   { "string", (PyCFunction) valpy_string, METH_VARARGS | METH_KEYWORDS,
1735     "string ([encoding] [, errors] [, length]) -> string\n\
1736 Return Unicode string representation of the value." },
1737   { "fetch_lazy", valpy_fetch_lazy, METH_NOARGS,
1738     "Fetches the value from the inferior, if it was lazy." },
1739   {NULL}  /* Sentinel */
1740 };
1741
1742 static PyNumberMethods value_object_as_number = {
1743   valpy_add,
1744   valpy_subtract,
1745   valpy_multiply,
1746 #ifndef IS_PY3K
1747   valpy_divide,
1748 #endif
1749   valpy_remainder,
1750   NULL,                       /* nb_divmod */
1751   valpy_power,                /* nb_power */
1752   valpy_negative,             /* nb_negative */
1753   valpy_positive,             /* nb_positive */
1754   valpy_absolute,             /* nb_absolute */
1755   valpy_nonzero,              /* nb_nonzero */
1756   valpy_invert,               /* nb_invert */
1757   valpy_lsh,                  /* nb_lshift */
1758   valpy_rsh,                  /* nb_rshift */
1759   valpy_and,                  /* nb_and */
1760   valpy_xor,                  /* nb_xor */
1761   valpy_or,                   /* nb_or */
1762 #ifdef IS_PY3K
1763   valpy_long,                 /* nb_int */
1764   NULL,                       /* reserved */
1765 #else
1766   NULL,                       /* nb_coerce */
1767   valpy_int,                  /* nb_int */
1768   valpy_long,                 /* nb_long */
1769 #endif
1770   valpy_float,                /* nb_float */
1771 #ifndef IS_PY3K
1772   NULL,                       /* nb_oct */
1773   NULL,                       /* nb_hex */
1774 #endif
1775   NULL,                       /* nb_inplace_add */
1776   NULL,                       /* nb_inplace_subtract */
1777   NULL,                       /* nb_inplace_multiply */
1778 #ifndef IS_PY3K
1779   NULL,                       /* nb_inplace_divide */
1780 #endif
1781   NULL,                       /* nb_inplace_remainder */
1782   NULL,                       /* nb_inplace_power */
1783   NULL,                       /* nb_inplace_lshift */
1784   NULL,                       /* nb_inplace_rshift */
1785   NULL,                       /* nb_inplace_and */
1786   NULL,                       /* nb_inplace_xor */
1787   NULL,                       /* nb_inplace_or */
1788   NULL,                       /* nb_floor_divide */
1789   valpy_divide,               /* nb_true_divide */
1790   NULL,                       /* nb_inplace_floor_divide */
1791   NULL,                       /* nb_inplace_true_divide */
1792 #ifndef HAVE_LIBPYTHON2_4
1793   /* This was added in Python 2.5.  */
1794   valpy_long,                 /* nb_index */
1795 #endif /* HAVE_LIBPYTHON2_4 */
1796 };
1797
1798 static PyMappingMethods value_object_as_mapping = {
1799   valpy_length,
1800   valpy_getitem,
1801   valpy_setitem
1802 };
1803
1804 PyTypeObject value_object_type = {
1805   PyVarObject_HEAD_INIT (NULL, 0)
1806   "gdb.Value",                    /*tp_name*/
1807   sizeof (value_object),          /*tp_basicsize*/
1808   0,                              /*tp_itemsize*/
1809   valpy_dealloc,                  /*tp_dealloc*/
1810   0,                              /*tp_print*/
1811   0,                              /*tp_getattr*/
1812   0,                              /*tp_setattr*/
1813   0,                              /*tp_compare*/
1814   0,                              /*tp_repr*/
1815   &value_object_as_number,        /*tp_as_number*/
1816   0,                              /*tp_as_sequence*/
1817   &value_object_as_mapping,       /*tp_as_mapping*/
1818   valpy_hash,                     /*tp_hash*/
1819   valpy_call,                     /*tp_call*/
1820   valpy_str,                      /*tp_str*/
1821   0,                              /*tp_getattro*/
1822   0,                              /*tp_setattro*/
1823   0,                              /*tp_as_buffer*/
1824   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES
1825   | Py_TPFLAGS_BASETYPE,          /*tp_flags*/
1826   "GDB value object",             /* tp_doc */
1827   0,                              /* tp_traverse */
1828   0,                              /* tp_clear */
1829   valpy_richcompare,              /* tp_richcompare */
1830   0,                              /* tp_weaklistoffset */
1831   0,                              /* tp_iter */
1832   0,                              /* tp_iternext */
1833   value_object_methods,           /* tp_methods */
1834   0,                              /* tp_members */
1835   value_object_getset,            /* tp_getset */
1836   0,                              /* tp_base */
1837   0,                              /* tp_dict */
1838   0,                              /* tp_descr_get */
1839   0,                              /* tp_descr_set */
1840   0,                              /* tp_dictoffset */
1841   0,                              /* tp_init */
1842   0,                              /* tp_alloc */
1843   valpy_new                       /* tp_new */
1844 };