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