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