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