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