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