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