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