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