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