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