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