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