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