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