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