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