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