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