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