]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/python/py-value.c
* valops.c (find_overload_match): Call do_cleanups before early
[thirdparty/binutils-gdb.git] / gdb / python / py-value.c
CommitLineData
7843261b
TJB
1/* Python interface to values.
2
7b6bb8da 3 Copyright (C) 2008, 2009, 2010, 2011 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
20#include "defs.h"
08c637de 21#include "gdb_assert.h"
7843261b
TJB
22#include "charset.h"
23#include "value.h"
24#include "exceptions.h"
25#include "language.h"
26#include "dfp.h"
79a45b7d 27#include "valprint.h"
5374244e 28#include "infcall.h"
f9ffd4bb 29#include "expression.h"
03f17ccf 30#include "cp-abi.h"
7843261b 31
7843261b
TJB
32#ifdef HAVE_PYTHON
33
34#include "python-internal.h"
35
36/* Even though Python scalar types directly map to host types, we use
b021a221 37 target types here to remain consistent with the values system in
7843261b
TJB
38 GDB (which uses target arithmetic). */
39
40/* Python's integer type corresponds to C's long type. */
d452c4bc 41#define builtin_type_pyint builtin_type (python_gdbarch)->builtin_long
7843261b
TJB
42
43/* Python's float type corresponds to C's double type. */
d452c4bc 44#define builtin_type_pyfloat builtin_type (python_gdbarch)->builtin_double
7843261b
TJB
45
46/* Python's long type corresponds to C's long long type. */
d452c4bc 47#define builtin_type_pylong builtin_type (python_gdbarch)->builtin_long_long
7843261b 48
595939de
PM
49/* Python's long type corresponds to C's long long type. Unsigned version. */
50#define builtin_type_upylong builtin_type \
51 (python_gdbarch)->builtin_unsigned_long_long
52
7843261b 53#define builtin_type_pybool \
d452c4bc 54 language_bool_type (python_language, python_gdbarch)
7843261b 55
3b7538c0 56#define builtin_type_pychar \
d452c4bc 57 language_string_char_type (python_language, python_gdbarch)
3b7538c0 58
4e7a5ef5 59typedef struct value_object {
7843261b 60 PyObject_HEAD
4e7a5ef5
TT
61 struct value_object *next;
62 struct value_object *prev;
7843261b 63 struct value *value;
c0c6f777 64 PyObject *address;
2c74e833 65 PyObject *type;
03f17ccf 66 PyObject *dynamic_type;
7843261b
TJB
67} value_object;
68
4e7a5ef5
TT
69/* List of all values which are currently exposed to Python. It is
70 maintained so that when an objfile is discarded, preserve_values
71 can copy the values' types if needed. */
72/* This variable is unnecessarily initialized to NULL in order to
73 work around a linker bug on MacOS. */
74static value_object *values_in_python = NULL;
75
7843261b
TJB
76/* Called by the Python interpreter when deallocating a value object. */
77static void
78valpy_dealloc (PyObject *obj)
79{
80 value_object *self = (value_object *) obj;
81
4e7a5ef5
TT
82 /* Remove SELF from the global list. */
83 if (self->prev)
84 self->prev->next = self->next;
85 else
86 {
87 gdb_assert (values_in_python == self);
88 values_in_python = self->next;
89 }
90 if (self->next)
91 self->next->prev = self->prev;
7843261b 92
77316f4c 93 value_free (self->value);
c0c6f777
TJB
94
95 if (self->address)
96 /* Use braces to appease gcc warning. *sigh* */
97 {
98 Py_DECREF (self->address);
99 }
100
2c74e833
TT
101 if (self->type)
102 {
103 Py_DECREF (self->type);
104 }
105
03f17ccf
TT
106 Py_XDECREF (self->dynamic_type);
107
7843261b
TJB
108 self->ob_type->tp_free (self);
109}
110
4e7a5ef5
TT
111/* Helper to push a Value object on the global list. */
112static void
113note_value (value_object *value_obj)
114{
115 value_obj->next = values_in_python;
116 if (value_obj->next)
117 value_obj->next->prev = value_obj;
118 value_obj->prev = NULL;
119 values_in_python = value_obj;
120}
121
8dc78533
JK
122/* Called when a new gdb.Value object needs to be allocated. Returns NULL on
123 error, with a python exception set. */
7843261b
TJB
124static PyObject *
125valpy_new (PyTypeObject *subtype, PyObject *args, PyObject *keywords)
126{
127 struct value *value = NULL; /* Initialize to appease gcc warning. */
128 value_object *value_obj;
7843261b
TJB
129
130 if (PyTuple_Size (args) != 1)
131 {
132 PyErr_SetString (PyExc_TypeError, _("Value object creation takes only "
133 "1 argument"));
134 return NULL;
135 }
136
137 value_obj = (value_object *) subtype->tp_alloc (subtype, 1);
138 if (value_obj == NULL)
139 {
140 PyErr_SetString (PyExc_MemoryError, _("Could not allocate memory to "
141 "create Value object."));
142 return NULL;
143 }
144
08c637de
TJB
145 value = convert_value_from_python (PyTuple_GetItem (args, 0));
146 if (value == NULL)
7843261b
TJB
147 {
148 subtype->tp_free (value_obj);
08c637de 149 return NULL;
7843261b
TJB
150 }
151
152 value_obj->value = value;
4e7a5ef5 153 value_incref (value);
c0c6f777 154 value_obj->address = NULL;
2c74e833 155 value_obj->type = NULL;
03f17ccf 156 value_obj->dynamic_type = NULL;
4e7a5ef5 157 note_value (value_obj);
7843261b
TJB
158
159 return (PyObject *) value_obj;
160}
161
4e7a5ef5
TT
162/* Iterate over all the Value objects, calling preserve_one_value on
163 each. */
164void
165preserve_python_values (struct objfile *objfile, htab_t copied_types)
166{
167 value_object *iter;
168
169 for (iter = values_in_python; iter; iter = iter->next)
170 preserve_one_value (iter->value, objfile, copied_types);
171}
172
7843261b
TJB
173/* Given a value of a pointer type, apply the C unary * operator to it. */
174static PyObject *
175valpy_dereference (PyObject *self, PyObject *args)
176{
177 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
178 volatile struct gdb_exception except;
179
180 TRY_CATCH (except, RETURN_MASK_ALL)
181 {
182 res_val = value_ind (((value_object *) self)->value);
183 }
184 GDB_PY_HANDLE_EXCEPTION (except);
185
186 return value_to_value_object (res_val);
187}
188
08c637de
TJB
189/* Return "&value". */
190static PyObject *
c0c6f777 191valpy_get_address (PyObject *self, void *closure)
08c637de
TJB
192{
193 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
c0c6f777 194 value_object *val_obj = (value_object *) self;
08c637de
TJB
195 volatile struct gdb_exception except;
196
c0c6f777 197 if (!val_obj->address)
08c637de 198 {
c0c6f777
TJB
199 TRY_CATCH (except, RETURN_MASK_ALL)
200 {
201 res_val = value_addr (val_obj->value);
202 }
203 if (except.reason < 0)
204 {
205 val_obj->address = Py_None;
206 Py_INCREF (Py_None);
207 }
208 else
209 val_obj->address = value_to_value_object (res_val);
08c637de 210 }
08c637de 211
c0c6f777
TJB
212 Py_INCREF (val_obj->address);
213
214 return val_obj->address;
08c637de
TJB
215}
216
2c74e833
TT
217/* Return type of the value. */
218static PyObject *
219valpy_get_type (PyObject *self, void *closure)
220{
221 value_object *obj = (value_object *) self;
d59b6f6c 222
2c74e833
TT
223 if (!obj->type)
224 {
225 obj->type = type_to_type_object (value_type (obj->value));
226 if (!obj->type)
03f17ccf 227 return NULL;
2c74e833
TT
228 }
229 Py_INCREF (obj->type);
230 return obj->type;
231}
232
03f17ccf
TT
233/* Return dynamic type of the value. */
234
235static PyObject *
236valpy_get_dynamic_type (PyObject *self, void *closure)
237{
238 value_object *obj = (value_object *) self;
239 volatile struct gdb_exception except;
240 struct type *type = NULL;
241
242 if (obj->dynamic_type != NULL)
243 {
244 Py_INCREF (obj->dynamic_type);
245 return obj->dynamic_type;
246 }
247
248 TRY_CATCH (except, RETURN_MASK_ALL)
249 {
250 struct value *val = obj->value;
251
252 type = value_type (val);
253 CHECK_TYPEDEF (type);
254
255 if (((TYPE_CODE (type) == TYPE_CODE_PTR)
256 || (TYPE_CODE (type) == TYPE_CODE_REF))
257 && (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_CLASS))
258 {
259 struct value *target;
260 int was_pointer = TYPE_CODE (type) == TYPE_CODE_PTR;
261
262 target = value_ind (val);
263 type = value_rtti_type (target, NULL, NULL, NULL);
264
265 if (type)
266 {
267 if (was_pointer)
268 type = lookup_pointer_type (type);
269 else
270 type = lookup_reference_type (type);
271 }
272 }
273 else if (TYPE_CODE (type) == TYPE_CODE_CLASS)
274 type = value_rtti_type (val, NULL, NULL, NULL);
275 else
276 {
277 /* Re-use object's static type. */
278 type = NULL;
279 }
280 }
281 GDB_PY_HANDLE_EXCEPTION (except);
282
283 if (type == NULL)
284 {
285 /* Ensure that the TYPE field is ready. */
286 if (!valpy_get_type (self, NULL))
287 return NULL;
288 /* We don't need to incref here, because valpy_get_type already
289 did it for us. */
290 obj->dynamic_type = obj->type;
291 }
292 else
293 obj->dynamic_type = type_to_type_object (type);
294
295 Py_INCREF (obj->dynamic_type);
296 return obj->dynamic_type;
297}
298
be759fcf
PM
299/* Implementation of gdb.Value.lazy_string ([encoding] [, length]) ->
300 string. Return a PyObject representing a lazy_string_object type.
301 A lazy string is a pointer to a string with an optional encoding and
302 length. If ENCODING is not given, encoding is set to None. If an
303 ENCODING is provided the encoding parameter is set to ENCODING, but
304 the string is not encoded. If LENGTH is provided then the length
305 parameter is set to LENGTH, otherwise length will be set to -1 (first
306 null of appropriate with). */
307static PyObject *
308valpy_lazy_string (PyObject *self, PyObject *args, PyObject *kw)
309{
74aedc46 310 gdb_py_longest length = -1;
be759fcf
PM
311 struct value *value = ((value_object *) self)->value;
312 const char *user_encoding = NULL;
313 static char *keywords[] = { "encoding", "length", NULL };
314 PyObject *str_obj;
315
74aedc46 316 if (!PyArg_ParseTupleAndKeywords (args, kw, "|s" GDB_PY_LL_ARG, keywords,
be759fcf
PM
317 &user_encoding, &length))
318 return NULL;
319
320 if (TYPE_CODE (value_type (value)) == TYPE_CODE_PTR)
321 value = value_ind (value);
322
323 str_obj = gdbpy_create_lazy_string_object (value_address (value), length,
9a2b4c1b
MS
324 user_encoding,
325 value_type (value));
be759fcf
PM
326
327 return (PyObject *) str_obj;
328}
329
fbb8f299
PM
330/* Implementation of gdb.Value.string ([encoding] [, errors]
331 [, length]) -> string. Return Unicode string with value contents.
332 If ENCODING is not given, the string is assumed to be encoded in
333 the target's charset. If LENGTH is provided, only fetch string to
334 the length provided. */
335
b6cb8e7d 336static PyObject *
cc924cad 337valpy_string (PyObject *self, PyObject *args, PyObject *kw)
b6cb8e7d 338{
f92adf3c 339 int length = -1;
b6cb8e7d
TJB
340 gdb_byte *buffer;
341 struct value *value = ((value_object *) self)->value;
342 volatile struct gdb_exception except;
343 PyObject *unicode;
344 const char *encoding = NULL;
345 const char *errors = NULL;
346 const char *user_encoding = NULL;
347 const char *la_encoding = NULL;
96c07c5b 348 struct type *char_type;
31158f0e 349 static char *keywords[] = { "encoding", "errors", "length", NULL };
b6cb8e7d 350
fbb8f299
PM
351 if (!PyArg_ParseTupleAndKeywords (args, kw, "|ssi", keywords,
352 &user_encoding, &errors, &length))
b6cb8e7d
TJB
353 return NULL;
354
355 TRY_CATCH (except, RETURN_MASK_ALL)
356 {
96c07c5b 357 LA_GET_STRING (value, &buffer, &length, &char_type, &la_encoding);
b6cb8e7d
TJB
358 }
359 GDB_PY_HANDLE_EXCEPTION (except);
360
361 encoding = (user_encoding && *user_encoding) ? user_encoding : la_encoding;
96c07c5b
TT
362 unicode = PyUnicode_Decode (buffer, length * TYPE_LENGTH (char_type),
363 encoding, errors);
b6cb8e7d
TJB
364 xfree (buffer);
365
366 return unicode;
367}
368
f9ffd4bb
TT
369/* A helper function that implements the various cast operators. */
370
2c74e833 371static PyObject *
f9ffd4bb 372valpy_do_cast (PyObject *self, PyObject *args, enum exp_opcode op)
2c74e833
TT
373{
374 PyObject *type_obj;
375 struct type *type;
376 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
377 volatile struct gdb_exception except;
378
379 if (! PyArg_ParseTuple (args, "O", &type_obj))
380 return NULL;
381
382 type = type_object_to_type (type_obj);
383 if (! type)
384 {
044c0f87
PM
385 PyErr_SetString (PyExc_RuntimeError,
386 _("Argument must be a type."));
2c74e833
TT
387 return NULL;
388 }
389
390 TRY_CATCH (except, RETURN_MASK_ALL)
391 {
f9ffd4bb
TT
392 struct value *val = ((value_object *) self)->value;
393
394 if (op == UNOP_DYNAMIC_CAST)
395 res_val = value_dynamic_cast (type, val);
396 else if (op == UNOP_REINTERPRET_CAST)
397 res_val = value_reinterpret_cast (type, val);
398 else
399 {
400 gdb_assert (op == UNOP_CAST);
401 res_val = value_cast (type, val);
402 }
2c74e833
TT
403 }
404 GDB_PY_HANDLE_EXCEPTION (except);
405
406 return value_to_value_object (res_val);
407}
408
f9ffd4bb
TT
409/* Implementation of the "cast" method. */
410
411static PyObject *
412valpy_cast (PyObject *self, PyObject *args)
413{
414 return valpy_do_cast (self, args, UNOP_CAST);
415}
416
417/* Implementation of the "dynamic_cast" method. */
418
419static PyObject *
420valpy_dynamic_cast (PyObject *self, PyObject *args)
421{
422 return valpy_do_cast (self, args, UNOP_DYNAMIC_CAST);
423}
424
425/* Implementation of the "reinterpret_cast" method. */
426
427static PyObject *
428valpy_reinterpret_cast (PyObject *self, PyObject *args)
429{
430 return valpy_do_cast (self, args, UNOP_REINTERPRET_CAST);
431}
432
7843261b
TJB
433static Py_ssize_t
434valpy_length (PyObject *self)
435{
436 /* We don't support getting the number of elements in a struct / class. */
437 PyErr_SetString (PyExc_NotImplementedError,
044c0f87 438 _("Invalid operation on gdb.Value."));
7843261b
TJB
439 return -1;
440}
441
442/* Given string name of an element inside structure, return its value
8dc78533 443 object. Returns NULL on error, with a python exception set. */
7843261b
TJB
444static PyObject *
445valpy_getitem (PyObject *self, PyObject *key)
446{
447 value_object *self_value = (value_object *) self;
08c637de 448 char *field = NULL;
570e2b1a 449 struct value *res_val = NULL;
7843261b
TJB
450 volatile struct gdb_exception except;
451
08c637de
TJB
452 if (gdbpy_is_string (key))
453 {
454 field = python_string_to_host_string (key);
455 if (field == NULL)
456 return NULL;
457 }
7843261b
TJB
458
459 TRY_CATCH (except, RETURN_MASK_ALL)
460 {
3c0ed299 461 struct value *tmp = self_value->value;
08c637de
TJB
462
463 if (field)
464 res_val = value_struct_elt (&tmp, NULL, field, 0, NULL);
465 else
466 {
467 /* Assume we are attempting an array access, and let the
468 value code throw an exception if the index has an invalid
469 type. */
470 struct value *idx = convert_value_from_python (key);
d59b6f6c 471
570e2b1a 472 if (idx != NULL)
2e4d963f
PM
473 {
474 /* Check the value's type is something that can be accessed via
475 a subscript. */
476 struct type *type;
d59b6f6c 477
2e4d963f
PM
478 tmp = coerce_ref (tmp);
479 type = check_typedef (value_type (tmp));
480 if (TYPE_CODE (type) != TYPE_CODE_ARRAY
481 && TYPE_CODE (type) != TYPE_CODE_PTR)
e10abd8f 482 error (_("Cannot subscript requested type."));
2e4d963f
PM
483 else
484 res_val = value_subscript (tmp, value_as_long (idx));
485 }
08c637de 486 }
7843261b 487 }
570e2b1a 488
06878dd2 489 xfree (field);
7843261b
TJB
490 GDB_PY_HANDLE_EXCEPTION (except);
491
06878dd2 492 return res_val ? value_to_value_object (res_val) : NULL;
7843261b
TJB
493}
494
495static int
496valpy_setitem (PyObject *self, PyObject *key, PyObject *value)
497{
498 PyErr_Format (PyExc_NotImplementedError,
499 _("Setting of struct elements is not currently supported."));
500 return -1;
501}
502
5374244e 503/* Called by the Python interpreter to perform an inferior function
8dc78533 504 call on the value. Returns NULL on error, with a python exception set. */
5374244e
PM
505static PyObject *
506valpy_call (PyObject *self, PyObject *args, PyObject *keywords)
507{
508 struct value *return_value = NULL;
509 Py_ssize_t args_count;
510 volatile struct gdb_exception except;
511 struct value *function = ((value_object *) self)->value;
512 struct value **vargs = NULL;
513 struct type *ftype = check_typedef (value_type (function));
514
515 if (TYPE_CODE (ftype) != TYPE_CODE_FUNC)
516 {
517 PyErr_SetString (PyExc_RuntimeError,
518 _("Value is not callable (not TYPE_CODE_FUNC)."));
519 return NULL;
520 }
521
522 args_count = PyTuple_Size (args);
523 if (args_count > 0)
524 {
525 int i;
526
527 vargs = alloca (sizeof (struct value *) * args_count);
528 for (i = 0; i < args_count; i++)
529 {
530 PyObject *item = PyTuple_GetItem (args, i);
531
532 if (item == NULL)
533 return NULL;
534
535 vargs[i] = convert_value_from_python (item);
536 if (vargs[i] == NULL)
537 return NULL;
538 }
539 }
540
541 TRY_CATCH (except, RETURN_MASK_ALL)
542 {
543 return_value = call_function_by_hand (function, args_count, vargs);
544 }
545 GDB_PY_HANDLE_EXCEPTION (except);
546
547 return value_to_value_object (return_value);
548}
549
7843261b
TJB
550/* Called by the Python interpreter to obtain string representation
551 of the object. */
552static PyObject *
553valpy_str (PyObject *self)
554{
555 char *s = NULL;
7843261b 556 PyObject *result;
79a45b7d 557 struct value_print_options opts;
7843261b
TJB
558 volatile struct gdb_exception except;
559
79a45b7d
TT
560 get_user_print_options (&opts);
561 opts.deref_ref = 0;
562
7843261b
TJB
563 TRY_CATCH (except, RETURN_MASK_ALL)
564 {
5fe41fbf
TT
565 struct ui_file *stb = mem_fileopen ();
566 struct cleanup *old_chain = make_cleanup_ui_file_delete (stb);
567
79a45b7d 568 common_val_print (((value_object *) self)->value, stb, 0,
d452c4bc 569 &opts, python_language);
759ef836 570 s = ui_file_xstrdup (stb, NULL);
5fe41fbf
TT
571
572 do_cleanups (old_chain);
7843261b
TJB
573 }
574 GDB_PY_HANDLE_EXCEPTION (except);
575
7843261b
TJB
576 result = PyUnicode_Decode (s, strlen (s), host_charset (), NULL);
577 xfree (s);
578
579 return result;
580}
581
def2b000
TJB
582/* Implements gdb.Value.is_optimized_out. */
583static PyObject *
584valpy_get_is_optimized_out (PyObject *self, void *closure)
585{
586 struct value *value = ((value_object *) self)->value;
587
588 if (value_optimized_out (value))
589 Py_RETURN_TRUE;
590
591 Py_RETURN_FALSE;
592}
593
88d4aea7
PM
594/* Calculate and return the address of the PyObject as the value of
595 the builtin __hash__ call. */
596static long
597valpy_hash (PyObject *self)
598{
599 return (long) (intptr_t) self;
600}
601
7843261b
TJB
602enum valpy_opcode
603{
604 VALPY_ADD,
605 VALPY_SUB,
606 VALPY_MUL,
607 VALPY_DIV,
608 VALPY_REM,
08c637de
TJB
609 VALPY_POW,
610 VALPY_LSH,
611 VALPY_RSH,
612 VALPY_BITAND,
613 VALPY_BITOR,
614 VALPY_BITXOR
7843261b
TJB
615};
616
617/* If TYPE is a reference, return the target; otherwise return TYPE. */
618#define STRIP_REFERENCE(TYPE) \
619 ((TYPE_CODE (TYPE) == TYPE_CODE_REF) ? (TYPE_TARGET_TYPE (TYPE)) : (TYPE))
620
621/* Returns a value object which is the result of applying the operation
8dc78533
JK
622 specified by OPCODE to the given arguments. Returns NULL on error, with
623 a python exception set. */
7843261b
TJB
624static PyObject *
625valpy_binop (enum valpy_opcode opcode, PyObject *self, PyObject *other)
626{
627 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
628 volatile struct gdb_exception except;
629
630 TRY_CATCH (except, RETURN_MASK_ALL)
631 {
632 struct value *arg1, *arg2;
633
634 /* If the gdb.Value object is the second operand, then it will be passed
635 to us as the OTHER argument, and SELF will be an entirely different
636 kind of object, altogether. Because of this, we can't assume self is
637 a gdb.Value object and need to convert it from python as well. */
638 arg1 = convert_value_from_python (self);
08c637de 639 if (arg1 == NULL)
cc924cad 640 break;
08c637de 641
7843261b 642 arg2 = convert_value_from_python (other);
08c637de 643 if (arg2 == NULL)
cc924cad 644 break;
7843261b
TJB
645
646 switch (opcode)
647 {
648 case VALPY_ADD:
649 {
650 struct type *ltype = value_type (arg1);
651 struct type *rtype = value_type (arg2);
652
653 CHECK_TYPEDEF (ltype);
654 ltype = STRIP_REFERENCE (ltype);
655 CHECK_TYPEDEF (rtype);
656 rtype = STRIP_REFERENCE (rtype);
657
2497b498
UW
658 if (TYPE_CODE (ltype) == TYPE_CODE_PTR
659 && is_integral_type (rtype))
660 res_val = value_ptradd (arg1, value_as_long (arg2));
661 else if (TYPE_CODE (rtype) == TYPE_CODE_PTR
662 && is_integral_type (ltype))
663 res_val = value_ptradd (arg2, value_as_long (arg1));
7843261b
TJB
664 else
665 res_val = value_binop (arg1, arg2, BINOP_ADD);
666 }
667 break;
668 case VALPY_SUB:
669 {
670 struct type *ltype = value_type (arg1);
671 struct type *rtype = value_type (arg2);
672
673 CHECK_TYPEDEF (ltype);
674 ltype = STRIP_REFERENCE (ltype);
675 CHECK_TYPEDEF (rtype);
676 rtype = STRIP_REFERENCE (rtype);
677
2497b498
UW
678 if (TYPE_CODE (ltype) == TYPE_CODE_PTR
679 && TYPE_CODE (rtype) == TYPE_CODE_PTR)
680 /* A ptrdiff_t for the target would be preferable here. */
681 res_val = value_from_longest (builtin_type_pyint,
682 value_ptrdiff (arg1, arg2));
683 else if (TYPE_CODE (ltype) == TYPE_CODE_PTR
684 && is_integral_type (rtype))
685 res_val = value_ptradd (arg1, - value_as_long (arg2));
7843261b
TJB
686 else
687 res_val = value_binop (arg1, arg2, BINOP_SUB);
688 }
689 break;
690 case VALPY_MUL:
691 res_val = value_binop (arg1, arg2, BINOP_MUL);
692 break;
693 case VALPY_DIV:
694 res_val = value_binop (arg1, arg2, BINOP_DIV);
695 break;
696 case VALPY_REM:
697 res_val = value_binop (arg1, arg2, BINOP_REM);
698 break;
699 case VALPY_POW:
700 res_val = value_binop (arg1, arg2, BINOP_EXP);
701 break;
08c637de
TJB
702 case VALPY_LSH:
703 res_val = value_binop (arg1, arg2, BINOP_LSH);
704 break;
705 case VALPY_RSH:
706 res_val = value_binop (arg1, arg2, BINOP_RSH);
707 break;
708 case VALPY_BITAND:
709 res_val = value_binop (arg1, arg2, BINOP_BITWISE_AND);
710 break;
711 case VALPY_BITOR:
712 res_val = value_binop (arg1, arg2, BINOP_BITWISE_IOR);
713 break;
714 case VALPY_BITXOR:
715 res_val = value_binop (arg1, arg2, BINOP_BITWISE_XOR);
716 break;
7843261b
TJB
717 }
718 }
719 GDB_PY_HANDLE_EXCEPTION (except);
720
cc924cad 721 return res_val ? value_to_value_object (res_val) : NULL;
7843261b
TJB
722}
723
724static PyObject *
725valpy_add (PyObject *self, PyObject *other)
726{
727 return valpy_binop (VALPY_ADD, self, other);
728}
729
730static PyObject *
731valpy_subtract (PyObject *self, PyObject *other)
732{
733 return valpy_binop (VALPY_SUB, self, other);
734}
735
736static PyObject *
737valpy_multiply (PyObject *self, PyObject *other)
738{
739 return valpy_binop (VALPY_MUL, self, other);
740}
741
742static PyObject *
743valpy_divide (PyObject *self, PyObject *other)
744{
745 return valpy_binop (VALPY_DIV, self, other);
746}
747
748static PyObject *
749valpy_remainder (PyObject *self, PyObject *other)
750{
751 return valpy_binop (VALPY_REM, self, other);
752}
753
754static PyObject *
755valpy_power (PyObject *self, PyObject *other, PyObject *unused)
756{
757 /* We don't support the ternary form of pow. I don't know how to express
758 that, so let's just throw NotImplementedError to at least do something
759 about it. */
760 if (unused != Py_None)
761 {
762 PyErr_SetString (PyExc_NotImplementedError,
763 "Invalid operation on gdb.Value.");
764 return NULL;
765 }
766
767 return valpy_binop (VALPY_POW, self, other);
768}
769
770static PyObject *
771valpy_negative (PyObject *self)
772{
773 struct value *val = NULL;
774 volatile struct gdb_exception except;
775
776 TRY_CATCH (except, RETURN_MASK_ALL)
777 {
778 val = value_neg (((value_object *) self)->value);
779 }
780 GDB_PY_HANDLE_EXCEPTION (except);
781
782 return value_to_value_object (val);
783}
784
785static PyObject *
786valpy_positive (PyObject *self)
787{
4e7a5ef5 788 return value_to_value_object (((value_object *) self)->value);
7843261b
TJB
789}
790
791static PyObject *
792valpy_absolute (PyObject *self)
793{
22601c15 794 struct value *value = ((value_object *) self)->value;
d59b6f6c 795
22601c15 796 if (value_less (value, value_zero (value_type (value), not_lval)))
7843261b
TJB
797 return valpy_negative (self);
798 else
799 return valpy_positive (self);
800}
801
802/* Implements boolean evaluation of gdb.Value. */
803static int
804valpy_nonzero (PyObject *self)
805{
806 value_object *self_value = (value_object *) self;
807 struct type *type;
808
809 type = check_typedef (value_type (self_value->value));
810
811 if (is_integral_type (type) || TYPE_CODE (type) == TYPE_CODE_PTR)
812 return !!value_as_long (self_value->value);
813 else if (TYPE_CODE (type) == TYPE_CODE_FLT)
814 return value_as_double (self_value->value) != 0;
815 else if (TYPE_CODE (type) == TYPE_CODE_DECFLOAT)
816 return !decimal_is_zero (value_contents (self_value->value),
e17a4113
UW
817 TYPE_LENGTH (type),
818 gdbarch_byte_order (get_type_arch (type)));
7843261b 819 else
96f73ba5
TT
820 /* All other values are True. */
821 return 1;
7843261b
TJB
822}
823
08c637de 824/* Implements ~ for value objects. */
7843261b 825static PyObject *
08c637de 826valpy_invert (PyObject *self)
7843261b 827{
08c637de 828 struct value *val = NULL;
7843261b
TJB
829 volatile struct gdb_exception except;
830
08c637de 831 TRY_CATCH (except, RETURN_MASK_ALL)
7843261b 832 {
08c637de
TJB
833 val = value_complement (((value_object *) self)->value);
834 }
835 GDB_PY_HANDLE_EXCEPTION (except);
7843261b 836
08c637de
TJB
837 return value_to_value_object (val);
838}
7843261b 839
08c637de
TJB
840/* Implements left shift for value objects. */
841static PyObject *
842valpy_lsh (PyObject *self, PyObject *other)
843{
844 return valpy_binop (VALPY_LSH, self, other);
845}
7843261b 846
08c637de
TJB
847/* Implements right shift for value objects. */
848static PyObject *
849valpy_rsh (PyObject *self, PyObject *other)
850{
851 return valpy_binop (VALPY_RSH, self, other);
852}
7843261b 853
08c637de
TJB
854/* Implements bitwise and for value objects. */
855static PyObject *
856valpy_and (PyObject *self, PyObject *other)
857{
858 return valpy_binop (VALPY_BITAND, self, other);
859}
7843261b 860
08c637de
TJB
861/* Implements bitwise or for value objects. */
862static PyObject *
863valpy_or (PyObject *self, PyObject *other)
864{
865 return valpy_binop (VALPY_BITOR, self, other);
866}
867
868/* Implements bitwise xor for value objects. */
869static PyObject *
870valpy_xor (PyObject *self, PyObject *other)
871{
872 return valpy_binop (VALPY_BITXOR, self, other);
873}
874
8dc78533
JK
875/* Implements comparison operations for value objects. Returns NULL on error,
876 with a python exception set. */
08c637de
TJB
877static PyObject *
878valpy_richcompare (PyObject *self, PyObject *other, int op)
879{
880 int result = 0;
881 struct value *value_other;
882 volatile struct gdb_exception except;
883
884 if (other == Py_None)
7843261b
TJB
885 /* Comparing with None is special. From what I can tell, in Python
886 None is smaller than anything else. */
887 switch (op) {
888 case Py_LT:
889 case Py_LE:
890 case Py_EQ:
891 Py_RETURN_FALSE;
892 case Py_NE:
893 case Py_GT:
894 case Py_GE:
895 Py_RETURN_TRUE;
896 default:
897 /* Can't happen. */
898 PyErr_SetString (PyExc_NotImplementedError,
044c0f87 899 _("Invalid operation on gdb.Value."));
7843261b
TJB
900 return NULL;
901 }
7843261b
TJB
902
903 TRY_CATCH (except, RETURN_MASK_ALL)
904 {
08c637de
TJB
905 value_other = convert_value_from_python (other);
906 if (value_other == NULL)
f02779d8
TT
907 {
908 result = -1;
909 break;
910 }
08c637de 911
7843261b
TJB
912 switch (op) {
913 case Py_LT:
914 result = value_less (((value_object *) self)->value, value_other);
915 break;
916 case Py_LE:
917 result = value_less (((value_object *) self)->value, value_other)
918 || value_equal (((value_object *) self)->value, value_other);
919 break;
920 case Py_EQ:
921 result = value_equal (((value_object *) self)->value, value_other);
922 break;
923 case Py_NE:
924 result = !value_equal (((value_object *) self)->value, value_other);
925 break;
926 case Py_GT:
927 result = value_less (value_other, ((value_object *) self)->value);
928 break;
929 case Py_GE:
930 result = value_less (value_other, ((value_object *) self)->value)
931 || value_equal (((value_object *) self)->value, value_other);
932 break;
933 default:
934 /* Can't happen. */
935 PyErr_SetString (PyExc_NotImplementedError,
044c0f87 936 _("Invalid operation on gdb.Value."));
f02779d8
TT
937 result = -1;
938 break;
7843261b
TJB
939 }
940 }
941 GDB_PY_HANDLE_EXCEPTION (except);
942
f02779d8
TT
943 /* In this case, the Python exception has already been set. */
944 if (result < 0)
945 return NULL;
946
7843261b
TJB
947 if (result == 1)
948 Py_RETURN_TRUE;
949
950 Py_RETURN_FALSE;
951}
952
08c637de
TJB
953/* Helper function to determine if a type is "int-like". */
954static int
955is_intlike (struct type *type, int ptr_ok)
956{
957 CHECK_TYPEDEF (type);
958 return (TYPE_CODE (type) == TYPE_CODE_INT
959 || TYPE_CODE (type) == TYPE_CODE_ENUM
960 || TYPE_CODE (type) == TYPE_CODE_BOOL
961 || TYPE_CODE (type) == TYPE_CODE_CHAR
962 || (ptr_ok && TYPE_CODE (type) == TYPE_CODE_PTR));
963}
964
965/* Implements conversion to int. */
966static PyObject *
967valpy_int (PyObject *self)
968{
969 struct value *value = ((value_object *) self)->value;
970 struct type *type = value_type (value);
971 LONGEST l = 0;
972 volatile struct gdb_exception except;
973
974 CHECK_TYPEDEF (type);
975 if (!is_intlike (type, 0))
976 {
044c0f87
PM
977 PyErr_SetString (PyExc_RuntimeError,
978 _("Cannot convert value to int."));
08c637de
TJB
979 return NULL;
980 }
981
982 TRY_CATCH (except, RETURN_MASK_ALL)
983 {
984 l = value_as_long (value);
985 }
986 GDB_PY_HANDLE_EXCEPTION (except);
987
74aedc46 988 return gdb_py_object_from_longest (l);
08c637de
TJB
989}
990
991/* Implements conversion to long. */
992static PyObject *
993valpy_long (PyObject *self)
994{
995 struct value *value = ((value_object *) self)->value;
996 struct type *type = value_type (value);
997 LONGEST l = 0;
998 volatile struct gdb_exception except;
999
1000 if (!is_intlike (type, 1))
1001 {
044c0f87
PM
1002 PyErr_SetString (PyExc_RuntimeError,
1003 _("Cannot convert value to long."));
08c637de
TJB
1004 return NULL;
1005 }
1006
1007 TRY_CATCH (except, RETURN_MASK_ALL)
1008 {
1009 l = value_as_long (value);
1010 }
1011 GDB_PY_HANDLE_EXCEPTION (except);
1012
74aedc46 1013 return gdb_py_long_from_longest (l);
08c637de
TJB
1014}
1015
1016/* Implements conversion to float. */
1017static PyObject *
1018valpy_float (PyObject *self)
1019{
1020 struct value *value = ((value_object *) self)->value;
1021 struct type *type = value_type (value);
1022 double d = 0;
1023 volatile struct gdb_exception except;
1024
1025 CHECK_TYPEDEF (type);
1026 if (TYPE_CODE (type) != TYPE_CODE_FLT)
1027 {
044c0f87
PM
1028 PyErr_SetString (PyExc_RuntimeError,
1029 _("Cannot convert value to float."));
08c637de
TJB
1030 return NULL;
1031 }
1032
1033 TRY_CATCH (except, RETURN_MASK_ALL)
1034 {
1035 d = value_as_double (value);
1036 }
1037 GDB_PY_HANDLE_EXCEPTION (except);
1038
1039 return PyFloat_FromDouble (d);
1040}
1041
7843261b
TJB
1042/* Returns an object for a value which is released from the all_values chain,
1043 so its lifetime is not bound to the execution of a command. */
1044PyObject *
1045value_to_value_object (struct value *val)
1046{
1047 value_object *val_obj;
1048
1049 val_obj = PyObject_New (value_object, &value_object_type);
1050 if (val_obj != NULL)
1051 {
1052 val_obj->value = val;
4e7a5ef5 1053 value_incref (val);
c0c6f777 1054 val_obj->address = NULL;
2c74e833 1055 val_obj->type = NULL;
03f17ccf 1056 val_obj->dynamic_type = NULL;
4e7a5ef5 1057 note_value (val_obj);
7843261b
TJB
1058 }
1059
1060 return (PyObject *) val_obj;
1061}
1062
4e7a5ef5
TT
1063/* Returns a borrowed reference to the struct value corresponding to
1064 the given value object. */
a6bac58e
TT
1065struct value *
1066value_object_to_value (PyObject *self)
1067{
1068 value_object *real;
d59b6f6c 1069
a6bac58e
TT
1070 if (! PyObject_TypeCheck (self, &value_object_type))
1071 return NULL;
1072 real = (value_object *) self;
1073 return real->value;
1074}
1075
7843261b 1076/* Try to convert a Python value to a gdb value. If the value cannot
4e7a5ef5
TT
1077 be converted, set a Python exception and return NULL. Returns a
1078 reference to a new value on the all_values chain. */
7843261b
TJB
1079
1080struct value *
1081convert_value_from_python (PyObject *obj)
1082{
1083 struct value *value = NULL; /* -Wall */
7843261b 1084 struct cleanup *old;
08c637de
TJB
1085 volatile struct gdb_exception except;
1086 int cmp;
7843261b 1087
08c637de 1088 gdb_assert (obj != NULL);
7843261b 1089
08c637de 1090 TRY_CATCH (except, RETURN_MASK_ALL)
7843261b 1091 {
08c637de
TJB
1092 if (PyBool_Check (obj))
1093 {
1094 cmp = PyObject_IsTrue (obj);
1095 if (cmp >= 0)
1096 value = value_from_longest (builtin_type_pybool, cmp);
1097 }
1098 else if (PyInt_Check (obj))
1099 {
1100 long l = PyInt_AsLong (obj);
7843261b 1101
08c637de
TJB
1102 if (! PyErr_Occurred ())
1103 value = value_from_longest (builtin_type_pyint, l);
1104 }
1105 else if (PyLong_Check (obj))
1106 {
1107 LONGEST l = PyLong_AsLongLong (obj);
7843261b 1108
595939de
PM
1109 if (PyErr_Occurred ())
1110 {
1111 /* If the error was an overflow, we can try converting to
1112 ULONGEST instead. */
1113 if (PyErr_ExceptionMatches (PyExc_OverflowError))
1114 {
1115 PyObject *etype, *evalue, *etraceback, *zero;
1116
1117 PyErr_Fetch (&etype, &evalue, &etraceback);
1118 zero = PyInt_FromLong (0);
1119
1120 /* Check whether obj is positive. */
1121 if (PyObject_RichCompareBool (obj, zero, Py_GT) > 0)
1122 {
1123 ULONGEST ul;
1124
1125 ul = PyLong_AsUnsignedLongLong (obj);
1126 if (! PyErr_Occurred ())
1127 value = value_from_ulongest (builtin_type_upylong, ul);
1128 }
1129 else
1130 /* There's nothing we can do. */
1131 PyErr_Restore (etype, evalue, etraceback);
1132
1133 Py_DECREF (zero);
1134 }
1135 }
1136 else
08c637de
TJB
1137 value = value_from_longest (builtin_type_pylong, l);
1138 }
1139 else if (PyFloat_Check (obj))
1140 {
1141 double d = PyFloat_AsDouble (obj);
7843261b 1142
08c637de
TJB
1143 if (! PyErr_Occurred ())
1144 value = value_from_double (builtin_type_pyfloat, d);
1145 }
1146 else if (gdbpy_is_string (obj))
1147 {
1148 char *s;
1149
1150 s = python_string_to_target_string (obj);
1151 if (s != NULL)
1152 {
1153 old = make_cleanup (xfree, s);
3b7538c0 1154 value = value_cstring (s, strlen (s), builtin_type_pychar);
08c637de
TJB
1155 do_cleanups (old);
1156 }
1157 }
1158 else if (PyObject_TypeCheck (obj, &value_object_type))
cc924cad 1159 value = value_copy (((value_object *) obj)->value);
be759fcf
PM
1160 else if (gdbpy_is_lazy_string (obj))
1161 {
1162 PyObject *result;
d59b6f6c 1163
fb6a3ed3 1164 result = PyObject_CallMethodObjArgs (obj, gdbpy_value_cst, NULL);
be759fcf
PM
1165 value = value_copy (((value_object *) result)->value);
1166 }
08c637de 1167 else
9a2b4c1b
MS
1168 PyErr_Format (PyExc_TypeError,
1169 _("Could not convert Python object: %s."),
08c637de
TJB
1170 PyString_AsString (PyObject_Str (obj)));
1171 }
1172 if (except.reason < 0)
1173 {
1174 PyErr_Format (except.reason == RETURN_QUIT
1175 ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
1176 "%s", except.message);
1177 return NULL;
1178 }
7843261b
TJB
1179
1180 return value;
1181}
1182
1183/* Returns value object in the ARGth position in GDB's history. */
1184PyObject *
08c637de 1185gdbpy_history (PyObject *self, PyObject *args)
7843261b
TJB
1186{
1187 int i;
1188 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
1189 volatile struct gdb_exception except;
1190
1191 if (!PyArg_ParseTuple (args, "i", &i))
1192 return NULL;
1193
1194 TRY_CATCH (except, RETURN_MASK_ALL)
1195 {
1196 res_val = access_value_history (i);
1197 }
1198 GDB_PY_HANDLE_EXCEPTION (except);
1199
1200 return value_to_value_object (res_val);
1201}
1202
595939de
PM
1203/* Returns 1 in OBJ is a gdb.Value object, 0 otherwise. */
1204
1205int
1206gdbpy_is_value_object (PyObject *obj)
1207{
1208 return PyObject_TypeCheck (obj, &value_object_type);
1209}
1210
7843261b
TJB
1211void
1212gdbpy_initialize_values (void)
1213{
7843261b
TJB
1214 if (PyType_Ready (&value_object_type) < 0)
1215 return;
1216
1217 Py_INCREF (&value_object_type);
1218 PyModule_AddObject (gdb_module, "Value", (PyObject *) &value_object_type);
1219
1220 values_in_python = NULL;
1221}
1222
2c74e833
TT
1223\f
1224
def2b000 1225static PyGetSetDef value_object_getset[] = {
c0c6f777
TJB
1226 { "address", valpy_get_address, NULL, "The address of the value.",
1227 NULL },
def2b000 1228 { "is_optimized_out", valpy_get_is_optimized_out, NULL,
9a2b4c1b
MS
1229 "Boolean telling whether the value is optimized "
1230 "out (i.e., not available).",
def2b000 1231 NULL },
2c74e833 1232 { "type", valpy_get_type, NULL, "Type of the value.", NULL },
03f17ccf
TT
1233 { "dynamic_type", valpy_get_dynamic_type, NULL,
1234 "Dynamic type of the value.", NULL },
def2b000
TJB
1235 {NULL} /* Sentinel */
1236};
1237
f9176c46 1238static PyMethodDef value_object_methods[] = {
2c74e833 1239 { "cast", valpy_cast, METH_VARARGS, "Cast the value to the supplied type." },
f9ffd4bb
TT
1240 { "dynamic_cast", valpy_dynamic_cast, METH_VARARGS,
1241 "dynamic_cast (gdb.Type) -> gdb.Value\n\
1242Cast the value to the supplied type, as if by the C++ dynamic_cast operator."
1243 },
1244 { "reinterpret_cast", valpy_reinterpret_cast, METH_VARARGS,
1245 "reinterpret_cast (gdb.Type) -> gdb.Value\n\
1246Cast the value to the supplied type, as if by the C++\n\
1247reinterpret_cast operator."
1248 },
f9176c46 1249 { "dereference", valpy_dereference, METH_NOARGS, "Dereferences the value." },
9a2b4c1b
MS
1250 { "lazy_string", (PyCFunction) valpy_lazy_string,
1251 METH_VARARGS | METH_KEYWORDS,
be759fcf
PM
1252 "lazy_string ([encoding] [, length]) -> lazy_string\n\
1253Return a lazy string representation of the value." },
cc924cad 1254 { "string", (PyCFunction) valpy_string, METH_VARARGS | METH_KEYWORDS,
fbb8f299 1255 "string ([encoding] [, errors] [, length]) -> string\n\
cc924cad 1256Return Unicode string representation of the value." },
f9176c46
PA
1257 {NULL} /* Sentinel */
1258};
1259
1260static PyNumberMethods value_object_as_number = {
1261 valpy_add,
1262 valpy_subtract,
1263 valpy_multiply,
1264 valpy_divide,
1265 valpy_remainder,
1266 NULL, /* nb_divmod */
1267 valpy_power, /* nb_power */
1268 valpy_negative, /* nb_negative */
1269 valpy_positive, /* nb_positive */
1270 valpy_absolute, /* nb_absolute */
08c637de
TJB
1271 valpy_nonzero, /* nb_nonzero */
1272 valpy_invert, /* nb_invert */
1273 valpy_lsh, /* nb_lshift */
1274 valpy_rsh, /* nb_rshift */
1275 valpy_and, /* nb_and */
1276 valpy_xor, /* nb_xor */
1277 valpy_or, /* nb_or */
1278 NULL, /* nb_coerce */
1279 valpy_int, /* nb_int */
1280 valpy_long, /* nb_long */
1281 valpy_float, /* nb_float */
1282 NULL, /* nb_oct */
1283 NULL /* nb_hex */
f9176c46
PA
1284};
1285
1286static PyMappingMethods value_object_as_mapping = {
1287 valpy_length,
1288 valpy_getitem,
1289 valpy_setitem
1290};
1291
1292PyTypeObject value_object_type = {
1293 PyObject_HEAD_INIT (NULL)
1294 0, /*ob_size*/
1295 "gdb.Value", /*tp_name*/
1296 sizeof (value_object), /*tp_basicsize*/
1297 0, /*tp_itemsize*/
1298 valpy_dealloc, /*tp_dealloc*/
1299 0, /*tp_print*/
1300 0, /*tp_getattr*/
1301 0, /*tp_setattr*/
1302 0, /*tp_compare*/
1303 0, /*tp_repr*/
1304 &value_object_as_number, /*tp_as_number*/
1305 0, /*tp_as_sequence*/
1306 &value_object_as_mapping, /*tp_as_mapping*/
88d4aea7 1307 valpy_hash, /*tp_hash*/
5374244e 1308 valpy_call, /*tp_call*/
f9176c46
PA
1309 valpy_str, /*tp_str*/
1310 0, /*tp_getattro*/
1311 0, /*tp_setattro*/
1312 0, /*tp_as_buffer*/
9a2b4c1b
MS
1313 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES
1314 | Py_TPFLAGS_BASETYPE, /*tp_flags*/
f9176c46
PA
1315 "GDB value object", /* tp_doc */
1316 0, /* tp_traverse */
1317 0, /* tp_clear */
1318 valpy_richcompare, /* tp_richcompare */
1319 0, /* tp_weaklistoffset */
1320 0, /* tp_iter */
1321 0, /* tp_iternext */
08c637de
TJB
1322 value_object_methods, /* tp_methods */
1323 0, /* tp_members */
def2b000 1324 value_object_getset, /* tp_getset */
08c637de
TJB
1325 0, /* tp_base */
1326 0, /* tp_dict */
1327 0, /* tp_descr_get */
1328 0, /* tp_descr_set */
1329 0, /* tp_dictoffset */
1330 0, /* tp_init */
1331 0, /* tp_alloc */
1332 valpy_new /* tp_new */
f9176c46
PA
1333};
1334
4e7a5ef5
TT
1335#else
1336
1337void
1338preserve_python_values (struct objfile *objfile, htab_t copied_types)
1339{
1340 /* Nothing. */
1341}
1342
7843261b 1343#endif /* HAVE_PYTHON */