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