2008-10-23 Paul Pluzhnikov <ppluzhnikov@google.com>
[deliverable/binutils-gdb.git] / gdb / python / python-value.c
1 /* Python interface to values.
2
3 Copyright (C) 2008 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 "charset.h"
22 #include "value.h"
23 #include "exceptions.h"
24 #include "language.h"
25 #include "dfp.h"
26
27 /* List of all values which are currently exposed to Python. It is
28 maintained so that when an objfile is discarded, preserve_values
29 can copy the values' types if needed. This is declared
30 unconditionally to reduce the number of uses of HAVE_PYTHON in the
31 generic code. */
32 struct value *values_in_python;
33
34 #ifdef HAVE_PYTHON
35
36 #include "python-internal.h"
37
38 /* Even though Python scalar types directly map to host types, we use
39 target types here to remain consistent with the the values system in
40 GDB (which uses target arithmetic). */
41
42 /* Python's integer type corresponds to C's long type. */
43 #define builtin_type_pyint builtin_type (current_gdbarch)->builtin_long
44
45 /* Python's float type corresponds to C's double type. */
46 #define builtin_type_pyfloat builtin_type (current_gdbarch)->builtin_double
47
48 /* Python's long type corresponds to C's long long type. */
49 #define builtin_type_pylong builtin_type (current_gdbarch)->builtin_long_long
50
51 #define builtin_type_pybool \
52 language_bool_type (current_language, current_gdbarch)
53
54 typedef struct {
55 PyObject_HEAD
56 struct value *value;
57 int owned_by_gdb;
58 } value_object;
59
60 /* Called by the Python interpreter when deallocating a value object. */
61 static void
62 valpy_dealloc (PyObject *obj)
63 {
64 value_object *self = (value_object *) obj;
65
66 value_remove_from_list (&values_in_python, self->value);
67
68 if (!self->owned_by_gdb)
69 value_free (self->value);
70 self->ob_type->tp_free (self);
71 }
72
73 /* Called when a new gdb.Value object needs to be allocated. */
74 static PyObject *
75 valpy_new (PyTypeObject *subtype, PyObject *args, PyObject *keywords)
76 {
77 struct value *value = NULL; /* Initialize to appease gcc warning. */
78 value_object *value_obj;
79 volatile struct gdb_exception except;
80
81 if (PyTuple_Size (args) != 1)
82 {
83 PyErr_SetString (PyExc_TypeError, _("Value object creation takes only "
84 "1 argument"));
85 return NULL;
86 }
87
88 value_obj = (value_object *) subtype->tp_alloc (subtype, 1);
89 if (value_obj == NULL)
90 {
91 PyErr_SetString (PyExc_MemoryError, _("Could not allocate memory to "
92 "create Value object."));
93 return NULL;
94 }
95
96 TRY_CATCH (except, RETURN_MASK_ALL)
97 {
98 value = convert_value_from_python (PyTuple_GetItem (args, 0));
99 }
100 if (except.reason < 0)
101 {
102 subtype->tp_free (value_obj);
103 return PyErr_Format (except.reason == RETURN_QUIT
104 ? PyExc_KeyboardInterrupt : PyExc_TypeError,
105 "%s", except.message);
106 }
107
108 value_obj->value = value;
109 value_obj->owned_by_gdb = 0;
110 release_value (value);
111 value_prepend_to_list (&values_in_python, value);
112
113 return (PyObject *) value_obj;
114 }
115
116 /* Given a value of a pointer type, apply the C unary * operator to it. */
117 static PyObject *
118 valpy_dereference (PyObject *self, PyObject *args)
119 {
120 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
121 volatile struct gdb_exception except;
122
123 TRY_CATCH (except, RETURN_MASK_ALL)
124 {
125 res_val = value_ind (((value_object *) self)->value);
126 }
127 GDB_PY_HANDLE_EXCEPTION (except);
128
129 return value_to_value_object (res_val);
130 }
131
132 #ifdef HAVE_LIBPYTHON2_4
133 static int
134 #else
135 static Py_ssize_t
136 #endif
137 valpy_length (PyObject *self)
138 {
139 /* We don't support getting the number of elements in a struct / class. */
140 PyErr_SetString (PyExc_NotImplementedError,
141 "Invalid operation on gdb.Value.");
142 return -1;
143 }
144
145 /* Given string name of an element inside structure, return its value
146 object. */
147 static PyObject *
148 valpy_getitem (PyObject *self, PyObject *key)
149 {
150 value_object *self_value = (value_object *) self;
151 char *field;
152 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
153 struct cleanup *old;
154 volatile struct gdb_exception except;
155
156 field = python_string_to_target_string (key);
157 if (field == NULL)
158 return NULL;
159
160 old = make_cleanup (xfree, field);
161
162 TRY_CATCH (except, RETURN_MASK_ALL)
163 {
164 struct value *tmp = self_value->value;
165 res_val = value_struct_elt (&tmp, NULL, field, 0, NULL);
166 }
167 GDB_PY_HANDLE_EXCEPTION (except);
168
169 do_cleanups (old);
170
171 return value_to_value_object (res_val);
172 }
173
174 static int
175 valpy_setitem (PyObject *self, PyObject *key, PyObject *value)
176 {
177 PyErr_Format (PyExc_NotImplementedError,
178 _("Setting of struct elements is not currently supported."));
179 return -1;
180 }
181
182 /* Called by the Python interpreter to obtain string representation
183 of the object. */
184 static PyObject *
185 valpy_str (PyObject *self)
186 {
187 char *s = NULL;
188 long dummy;
189 struct ui_file *stb;
190 struct cleanup *old_chain;
191 PyObject *result;
192 volatile struct gdb_exception except;
193
194 stb = mem_fileopen ();
195 old_chain = make_cleanup_ui_file_delete (stb);
196
197 TRY_CATCH (except, RETURN_MASK_ALL)
198 {
199 common_val_print (((value_object *) self)->value, stb, 0, 0, 0,
200 Val_pretty_default, current_language);
201 s = ui_file_xstrdup (stb, &dummy);
202 }
203 GDB_PY_HANDLE_EXCEPTION (except);
204
205 do_cleanups (old_chain);
206
207 result = PyUnicode_Decode (s, strlen (s), host_charset (), NULL);
208 xfree (s);
209
210 return result;
211 }
212
213 enum valpy_opcode
214 {
215 VALPY_ADD,
216 VALPY_SUB,
217 VALPY_MUL,
218 VALPY_DIV,
219 VALPY_REM,
220 VALPY_POW
221 };
222
223 /* If TYPE is a reference, return the target; otherwise return TYPE. */
224 #define STRIP_REFERENCE(TYPE) \
225 ((TYPE_CODE (TYPE) == TYPE_CODE_REF) ? (TYPE_TARGET_TYPE (TYPE)) : (TYPE))
226
227 /* Returns a value object which is the result of applying the operation
228 specified by OPCODE to the given arguments. */
229 static PyObject *
230 valpy_binop (enum valpy_opcode opcode, PyObject *self, PyObject *other)
231 {
232 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
233 volatile struct gdb_exception except;
234
235 TRY_CATCH (except, RETURN_MASK_ALL)
236 {
237 struct value *arg1, *arg2;
238
239 /* If the gdb.Value object is the second operand, then it will be passed
240 to us as the OTHER argument, and SELF will be an entirely different
241 kind of object, altogether. Because of this, we can't assume self is
242 a gdb.Value object and need to convert it from python as well. */
243 arg1 = convert_value_from_python (self);
244 arg2 = convert_value_from_python (other);
245
246 switch (opcode)
247 {
248 case VALPY_ADD:
249 {
250 struct type *ltype = value_type (arg1);
251 struct type *rtype = value_type (arg2);
252
253 CHECK_TYPEDEF (ltype);
254 ltype = STRIP_REFERENCE (ltype);
255 CHECK_TYPEDEF (rtype);
256 rtype = STRIP_REFERENCE (rtype);
257
258 if (TYPE_CODE (ltype) == TYPE_CODE_PTR)
259 res_val = value_ptradd (arg1, arg2);
260 else if (TYPE_CODE (rtype) == TYPE_CODE_PTR)
261 res_val = value_ptradd (arg2, arg1);
262 else
263 res_val = value_binop (arg1, arg2, BINOP_ADD);
264 }
265 break;
266 case VALPY_SUB:
267 {
268 struct type *ltype = value_type (arg1);
269 struct type *rtype = value_type (arg2);
270
271 CHECK_TYPEDEF (ltype);
272 ltype = STRIP_REFERENCE (ltype);
273 CHECK_TYPEDEF (rtype);
274 rtype = STRIP_REFERENCE (rtype);
275
276 if (TYPE_CODE (ltype) == TYPE_CODE_PTR)
277 {
278 if (TYPE_CODE (rtype) == TYPE_CODE_PTR)
279 /* A ptrdiff_t for the target would be preferable
280 here. */
281 res_val = value_from_longest (builtin_type_pyint,
282 value_ptrdiff (arg1, arg2));
283 else
284 res_val = value_ptrsub (arg1, arg2);
285 }
286 else
287 res_val = value_binop (arg1, arg2, BINOP_SUB);
288 }
289 break;
290 case VALPY_MUL:
291 res_val = value_binop (arg1, arg2, BINOP_MUL);
292 break;
293 case VALPY_DIV:
294 res_val = value_binop (arg1, arg2, BINOP_DIV);
295 break;
296 case VALPY_REM:
297 res_val = value_binop (arg1, arg2, BINOP_REM);
298 break;
299 case VALPY_POW:
300 res_val = value_binop (arg1, arg2, BINOP_EXP);
301 break;
302 }
303 }
304 GDB_PY_HANDLE_EXCEPTION (except);
305
306 return value_to_value_object (res_val);
307 }
308
309 static PyObject *
310 valpy_add (PyObject *self, PyObject *other)
311 {
312 return valpy_binop (VALPY_ADD, self, other);
313 }
314
315 static PyObject *
316 valpy_subtract (PyObject *self, PyObject *other)
317 {
318 return valpy_binop (VALPY_SUB, self, other);
319 }
320
321 static PyObject *
322 valpy_multiply (PyObject *self, PyObject *other)
323 {
324 return valpy_binop (VALPY_MUL, self, other);
325 }
326
327 static PyObject *
328 valpy_divide (PyObject *self, PyObject *other)
329 {
330 return valpy_binop (VALPY_DIV, self, other);
331 }
332
333 static PyObject *
334 valpy_remainder (PyObject *self, PyObject *other)
335 {
336 return valpy_binop (VALPY_REM, self, other);
337 }
338
339 static PyObject *
340 valpy_power (PyObject *self, PyObject *other, PyObject *unused)
341 {
342 /* We don't support the ternary form of pow. I don't know how to express
343 that, so let's just throw NotImplementedError to at least do something
344 about it. */
345 if (unused != Py_None)
346 {
347 PyErr_SetString (PyExc_NotImplementedError,
348 "Invalid operation on gdb.Value.");
349 return NULL;
350 }
351
352 return valpy_binop (VALPY_POW, self, other);
353 }
354
355 static PyObject *
356 valpy_negative (PyObject *self)
357 {
358 struct value *val = NULL;
359 volatile struct gdb_exception except;
360
361 TRY_CATCH (except, RETURN_MASK_ALL)
362 {
363 val = value_neg (((value_object *) self)->value);
364 }
365 GDB_PY_HANDLE_EXCEPTION (except);
366
367 return value_to_value_object (val);
368 }
369
370 static PyObject *
371 valpy_positive (PyObject *self)
372 {
373 struct value *copy = value_copy (((value_object *) self)->value);
374
375 return value_to_value_object (copy);
376 }
377
378 static PyObject *
379 valpy_absolute (PyObject *self)
380 {
381 if (value_less (((value_object *) self)->value,
382 value_from_longest (builtin_type_int8, 0)))
383 return valpy_negative (self);
384 else
385 return valpy_positive (self);
386 }
387
388 /* Implements boolean evaluation of gdb.Value. */
389 static int
390 valpy_nonzero (PyObject *self)
391 {
392 value_object *self_value = (value_object *) self;
393 struct type *type;
394
395 type = check_typedef (value_type (self_value->value));
396
397 if (is_integral_type (type) || TYPE_CODE (type) == TYPE_CODE_PTR)
398 return !!value_as_long (self_value->value);
399 else if (TYPE_CODE (type) == TYPE_CODE_FLT)
400 return value_as_double (self_value->value) != 0;
401 else if (TYPE_CODE (type) == TYPE_CODE_DECFLOAT)
402 return !decimal_is_zero (value_contents (self_value->value),
403 TYPE_LENGTH (type));
404 else
405 {
406 PyErr_SetString (PyExc_TypeError, _("Attempted truth testing on invalid "
407 "gdb.Value type."));
408 return 0;
409 }
410 }
411
412 /* Implements comparison operations for value objects. */
413 static PyObject *
414 valpy_richcompare (PyObject *self, PyObject *other, int op)
415 {
416 int result = 0;
417 struct value *value_self, *value_other;
418 volatile struct gdb_exception except;
419
420 if (PyObject_TypeCheck (other, &value_object_type))
421 value_other = ((value_object *) other)->value;
422 else if (PyInt_Check (other))
423 {
424 LONGEST l;
425
426 l = PyInt_AsLong (other);
427 if (PyErr_Occurred ())
428 return NULL;
429
430 value_other = value_from_longest (builtin_type_pyint, l);
431 }
432 else if (PyFloat_Check (other))
433 {
434 DOUBLEST d;
435
436 d = PyFloat_AsDouble (other);
437 if (PyErr_Occurred ())
438 return NULL;
439
440 value_other = value_from_double (builtin_type_pyfloat, d);
441 }
442 else if (PyString_Check (other) || PyUnicode_Check (other))
443 {
444 char *str;
445
446 str = python_string_to_target_string (other);
447 value_other = value_from_string (str);
448 xfree (str);
449 }
450 else if (other == Py_None)
451 /* Comparing with None is special. From what I can tell, in Python
452 None is smaller than anything else. */
453 switch (op) {
454 case Py_LT:
455 case Py_LE:
456 case Py_EQ:
457 Py_RETURN_FALSE;
458 case Py_NE:
459 case Py_GT:
460 case Py_GE:
461 Py_RETURN_TRUE;
462 default:
463 /* Can't happen. */
464 PyErr_SetString (PyExc_NotImplementedError,
465 "Invalid operation on gdb.Value.");
466 return NULL;
467 }
468 else
469 {
470 PyErr_SetString (PyExc_NotImplementedError,
471 "Operation not supported on gdb.Value of this type.");
472 return NULL;
473 }
474
475 TRY_CATCH (except, RETURN_MASK_ALL)
476 {
477 switch (op) {
478 case Py_LT:
479 result = value_less (((value_object *) self)->value, value_other);
480 break;
481 case Py_LE:
482 result = value_less (((value_object *) self)->value, value_other)
483 || value_equal (((value_object *) self)->value, value_other);
484 break;
485 case Py_EQ:
486 result = value_equal (((value_object *) self)->value, value_other);
487 break;
488 case Py_NE:
489 result = !value_equal (((value_object *) self)->value, value_other);
490 break;
491 case Py_GT:
492 result = value_less (value_other, ((value_object *) self)->value);
493 break;
494 case Py_GE:
495 result = value_less (value_other, ((value_object *) self)->value)
496 || value_equal (((value_object *) self)->value, value_other);
497 break;
498 default:
499 /* Can't happen. */
500 PyErr_SetString (PyExc_NotImplementedError,
501 "Invalid operation on gdb.Value.");
502 return NULL;
503 }
504 }
505 GDB_PY_HANDLE_EXCEPTION (except);
506
507 if (result == 1)
508 Py_RETURN_TRUE;
509
510 Py_RETURN_FALSE;
511 }
512
513 /* Returns an object for a value which is released from the all_values chain,
514 so its lifetime is not bound to the execution of a command. */
515 PyObject *
516 value_to_value_object (struct value *val)
517 {
518 value_object *val_obj;
519
520 val_obj = PyObject_New (value_object, &value_object_type);
521 if (val_obj != NULL)
522 {
523 val_obj->value = val;
524 val_obj->owned_by_gdb = 0;
525 release_value (val);
526 value_prepend_to_list (&values_in_python, val);
527 }
528
529 return (PyObject *) val_obj;
530 }
531
532 /* Try to convert a Python value to a gdb value. If the value cannot
533 be converted, throw a gdb exception. */
534
535 struct value *
536 convert_value_from_python (PyObject *obj)
537 {
538 struct value *value = NULL; /* -Wall */
539 PyObject *target_str, *unicode_str;
540 struct cleanup *old;
541
542 if (! obj)
543 error (_("Internal error while converting Python value."));
544
545 if (PyBool_Check (obj))
546 value = value_from_longest (builtin_type_pybool, obj == Py_True);
547 else if (PyInt_Check (obj))
548 value = value_from_longest (builtin_type_pyint, PyInt_AsLong (obj));
549 else if (PyLong_Check (obj))
550 {
551 LONGEST l = PyLong_AsLongLong (obj);
552 if (! PyErr_Occurred ())
553 value = value_from_longest (builtin_type_pylong, l);
554 }
555 else if (PyFloat_Check (obj))
556 {
557 double d = PyFloat_AsDouble (obj);
558 if (! PyErr_Occurred ())
559 value = value_from_double (builtin_type_pyfloat, d);
560 }
561 else if (PyString_Check (obj) || PyUnicode_Check (obj))
562 {
563 char *s;
564
565 s = python_string_to_target_string (obj);
566 if (s == NULL)
567 return NULL;
568
569 old = make_cleanup (xfree, s);
570 value = value_from_string (s);
571 do_cleanups (old);
572 }
573 else if (PyObject_TypeCheck (obj, &value_object_type))
574 value = ((value_object *) obj)->value;
575 else
576 error (_("Could not convert Python object: %s"),
577 PyString_AsString (PyObject_Str (obj)));
578
579 if (PyErr_Occurred ())
580 error (_("Error converting Python value."));
581
582 return value;
583 }
584
585 /* Returns value object in the ARGth position in GDB's history. */
586 PyObject *
587 gdbpy_get_value_from_history (PyObject *self, PyObject *args)
588 {
589 int i;
590 struct value *res_val = NULL; /* Initialize to appease gcc warning. */
591 volatile struct gdb_exception except;
592
593 if (!PyArg_ParseTuple (args, "i", &i))
594 return NULL;
595
596 TRY_CATCH (except, RETURN_MASK_ALL)
597 {
598 res_val = access_value_history (i);
599 }
600 GDB_PY_HANDLE_EXCEPTION (except);
601
602 return value_to_value_object (res_val);
603 }
604
605 void
606 gdbpy_initialize_values (void)
607 {
608 value_object_type.tp_new = valpy_new;
609 if (PyType_Ready (&value_object_type) < 0)
610 return;
611
612 Py_INCREF (&value_object_type);
613 PyModule_AddObject (gdb_module, "Value", (PyObject *) &value_object_type);
614
615 values_in_python = NULL;
616 }
617
618 static PyMethodDef value_object_methods[] = {
619 { "dereference", valpy_dereference, METH_NOARGS, "Dereferences the value." },
620 {NULL} /* Sentinel */
621 };
622
623 static PyNumberMethods value_object_as_number = {
624 valpy_add,
625 valpy_subtract,
626 valpy_multiply,
627 valpy_divide,
628 valpy_remainder,
629 NULL, /* nb_divmod */
630 valpy_power, /* nb_power */
631 valpy_negative, /* nb_negative */
632 valpy_positive, /* nb_positive */
633 valpy_absolute, /* nb_absolute */
634 valpy_nonzero /* nb_nonzero */
635 };
636
637 static PyMappingMethods value_object_as_mapping = {
638 valpy_length,
639 valpy_getitem,
640 valpy_setitem
641 };
642
643 PyTypeObject value_object_type = {
644 PyObject_HEAD_INIT (NULL)
645 0, /*ob_size*/
646 "gdb.Value", /*tp_name*/
647 sizeof (value_object), /*tp_basicsize*/
648 0, /*tp_itemsize*/
649 valpy_dealloc, /*tp_dealloc*/
650 0, /*tp_print*/
651 0, /*tp_getattr*/
652 0, /*tp_setattr*/
653 0, /*tp_compare*/
654 0, /*tp_repr*/
655 &value_object_as_number, /*tp_as_number*/
656 0, /*tp_as_sequence*/
657 &value_object_as_mapping, /*tp_as_mapping*/
658 0, /*tp_hash */
659 0, /*tp_call*/
660 valpy_str, /*tp_str*/
661 0, /*tp_getattro*/
662 0, /*tp_setattro*/
663 0, /*tp_as_buffer*/
664 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /*tp_flags*/
665 "GDB value object", /* tp_doc */
666 0, /* tp_traverse */
667 0, /* tp_clear */
668 valpy_richcompare, /* tp_richcompare */
669 0, /* tp_weaklistoffset */
670 0, /* tp_iter */
671 0, /* tp_iternext */
672 value_object_methods /* tp_methods */
673 };
674
675 #endif /* HAVE_PYTHON */
This page took 0.043843 seconds and 5 git commands to generate.