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