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