1 /* Python interface to types.
3 Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
22 #include "exceptions.h"
23 #include "python-internal.h"
26 #include "cp-support.h"
31 typedef struct pyty_type_object
36 /* If a Type object is associated with an objfile, it is kept on a
37 doubly-linked list, rooted in the objfile. This lets us copy the
38 underlying struct type when the objfile is deleted. */
39 struct pyty_type_object *prev;
40 struct pyty_type_object *next;
43 static PyTypeObject type_object_type;
46 typedef struct pyty_field_object
50 /* Dictionary holding our attributes. */
54 static PyTypeObject field_object_type;
56 /* This is used to initialize various gdb.TYPE_ constants. */
65 #define ENTRY(X) { X, #X }
67 static struct pyty_code pyty_codes[] =
69 ENTRY (TYPE_CODE_PTR),
70 ENTRY (TYPE_CODE_ARRAY),
71 ENTRY (TYPE_CODE_STRUCT),
72 ENTRY (TYPE_CODE_UNION),
73 ENTRY (TYPE_CODE_ENUM),
74 ENTRY (TYPE_CODE_FLAGS),
75 ENTRY (TYPE_CODE_FUNC),
76 ENTRY (TYPE_CODE_INT),
77 ENTRY (TYPE_CODE_FLT),
78 ENTRY (TYPE_CODE_VOID),
79 ENTRY (TYPE_CODE_SET),
80 ENTRY (TYPE_CODE_RANGE),
81 ENTRY (TYPE_CODE_STRING),
82 ENTRY (TYPE_CODE_BITSTRING),
83 ENTRY (TYPE_CODE_ERROR),
84 ENTRY (TYPE_CODE_METHOD),
85 ENTRY (TYPE_CODE_METHODPTR),
86 ENTRY (TYPE_CODE_MEMBERPTR),
87 ENTRY (TYPE_CODE_REF),
88 ENTRY (TYPE_CODE_CHAR),
89 ENTRY (TYPE_CODE_BOOL),
90 ENTRY (TYPE_CODE_COMPLEX),
91 ENTRY (TYPE_CODE_TYPEDEF),
92 ENTRY (TYPE_CODE_NAMESPACE),
93 ENTRY (TYPE_CODE_DECFLOAT),
94 ENTRY (TYPE_CODE_INTERNAL_FUNCTION),
95 { TYPE_CODE_UNDEF, NULL }
101 field_dealloc (PyObject *obj)
103 field_object *f = (field_object *) obj;
105 Py_XDECREF (f->dict);
106 f->ob_type->tp_free (obj);
112 field_object *result = PyObject_New (field_object, &field_object_type);
116 result->dict = PyDict_New ();
123 return (PyObject *) result;
128 /* Return the code for this type. */
130 typy_get_code (PyObject *self, void *closure)
132 struct type *type = ((type_object *) self)->type;
134 return PyInt_FromLong (TYPE_CODE (type));
137 /* Helper function for typy_fields which converts a single field to a
138 dictionary. Returns NULL on error. */
140 convert_field (struct type *type, int field)
142 PyObject *result = field_new ();
148 if (!field_is_static (&TYPE_FIELD (type, field)))
150 arg = PyLong_FromLong (TYPE_FIELD_BITPOS (type, field));
154 if (PyObject_SetAttrString (result, "bitpos", arg) < 0)
158 if (TYPE_FIELD_NAME (type, field))
159 arg = PyString_FromString (TYPE_FIELD_NAME (type, field));
167 if (PyObject_SetAttrString (result, "name", arg) < 0)
170 arg = TYPE_FIELD_ARTIFICIAL (type, field) ? Py_True : Py_False;
172 if (PyObject_SetAttrString (result, "artificial", arg) < 0)
175 if (TYPE_CODE (type) == TYPE_CODE_CLASS)
176 arg = field < TYPE_N_BASECLASSES (type) ? Py_True : Py_False;
180 if (PyObject_SetAttrString (result, "is_base_class", arg) < 0)
183 arg = PyLong_FromLong (TYPE_FIELD_BITSIZE (type, field));
186 if (PyObject_SetAttrString (result, "bitsize", arg) < 0)
189 /* A field can have a NULL type in some situations. */
190 if (TYPE_FIELD_TYPE (type, field) == NULL)
196 arg = type_to_type_object (TYPE_FIELD_TYPE (type, field));
199 if (PyObject_SetAttrString (result, "type", arg) < 0)
211 /* Return a sequence of all fields. Each field is a dictionary with
212 some pre-defined keys. */
214 typy_fields (PyObject *self, PyObject *args)
218 struct type *type = ((type_object *) self)->type;
220 /* We would like to make a tuple here, make fields immutable, and
221 then memoize the result (and perhaps make Field.type() lazy).
222 However, that can lead to cycles. */
223 result = PyList_New (0);
225 for (i = 0; i < TYPE_NFIELDS (type); ++i)
227 PyObject *dict = convert_field (type, i);
234 if (PyList_Append (result, dict))
245 /* Return the type's tag, or None. */
247 typy_get_tag (PyObject *self, void *closure)
249 struct type *type = ((type_object *) self)->type;
251 if (!TYPE_TAG_NAME (type))
253 return PyString_FromString (TYPE_TAG_NAME (type));
256 /* Return the type, stripped of typedefs. */
258 typy_strip_typedefs (PyObject *self, PyObject *args)
260 struct type *type = ((type_object *) self)->type;
262 return type_to_type_object (check_typedef (type));
265 /* Return a Type object which represents a pointer to SELF. */
267 typy_pointer (PyObject *self, PyObject *args)
269 struct type *type = ((type_object *) self)->type;
270 volatile struct gdb_exception except;
272 TRY_CATCH (except, RETURN_MASK_ALL)
274 type = lookup_pointer_type (type);
276 GDB_PY_HANDLE_EXCEPTION (except);
278 return type_to_type_object (type);
281 /* Return the range of a type represented by SELF. The return type is
282 a tuple. The first element of the tuple contains the low bound,
283 while the second element of the tuple contains the high bound. */
285 typy_range (PyObject *self, PyObject *args)
287 struct type *type = ((type_object *) self)->type;
289 PyObject *low_bound = NULL, *high_bound = NULL;
290 /* Initialize these to appease GCC warnings. */
291 LONGEST low = 0, high = 0;
293 if (TYPE_CODE (type) != TYPE_CODE_ARRAY
294 && TYPE_CODE (type) != TYPE_CODE_STRING
295 && TYPE_CODE (type) != TYPE_CODE_RANGE)
297 PyErr_SetString (PyExc_RuntimeError,
298 _("This type does not have a range."));
302 switch (TYPE_CODE (type))
304 case TYPE_CODE_ARRAY:
305 case TYPE_CODE_STRING:
306 low = TYPE_LOW_BOUND (TYPE_INDEX_TYPE (type));
307 high = TYPE_HIGH_BOUND (TYPE_INDEX_TYPE (type));
309 case TYPE_CODE_RANGE:
310 low = TYPE_LOW_BOUND (type);
311 high = TYPE_HIGH_BOUND (type);
315 low_bound = PyLong_FromLong (low);
319 high_bound = PyLong_FromLong (high);
323 result = PyTuple_New (2);
327 if (PyTuple_SetItem (result, 0, low_bound) != 0)
332 if (PyTuple_SetItem (result, 1, high_bound) != 0)
334 Py_DECREF (high_bound);
341 Py_XDECREF (high_bound);
342 Py_XDECREF (low_bound);
346 /* Return a Type object which represents a reference to SELF. */
348 typy_reference (PyObject *self, PyObject *args)
350 struct type *type = ((type_object *) self)->type;
351 volatile struct gdb_exception except;
353 TRY_CATCH (except, RETURN_MASK_ALL)
355 type = lookup_reference_type (type);
357 GDB_PY_HANDLE_EXCEPTION (except);
359 return type_to_type_object (type);
362 /* Return a Type object which represents the target type of SELF. */
364 typy_target (PyObject *self, PyObject *args)
366 struct type *type = ((type_object *) self)->type;
368 if (!TYPE_TARGET_TYPE (type))
370 PyErr_SetString (PyExc_RuntimeError,
371 _("Type does not have a target."));
375 return type_to_type_object (TYPE_TARGET_TYPE (type));
378 /* Return a const-qualified type variant. */
380 typy_const (PyObject *self, PyObject *args)
382 struct type *type = ((type_object *) self)->type;
383 volatile struct gdb_exception except;
385 TRY_CATCH (except, RETURN_MASK_ALL)
387 type = make_cv_type (1, 0, type, NULL);
389 GDB_PY_HANDLE_EXCEPTION (except);
391 return type_to_type_object (type);
394 /* Return a volatile-qualified type variant. */
396 typy_volatile (PyObject *self, PyObject *args)
398 struct type *type = ((type_object *) self)->type;
399 volatile struct gdb_exception except;
401 TRY_CATCH (except, RETURN_MASK_ALL)
403 type = make_cv_type (0, 1, type, NULL);
405 GDB_PY_HANDLE_EXCEPTION (except);
407 return type_to_type_object (type);
410 /* Return an unqualified type variant. */
412 typy_unqualified (PyObject *self, PyObject *args)
414 struct type *type = ((type_object *) self)->type;
415 volatile struct gdb_exception except;
417 TRY_CATCH (except, RETURN_MASK_ALL)
419 type = make_cv_type (0, 0, type, NULL);
421 GDB_PY_HANDLE_EXCEPTION (except);
423 return type_to_type_object (type);
426 /* Return the size of the type represented by SELF, in bytes. */
428 typy_get_sizeof (PyObject *self, void *closure)
430 struct type *type = ((type_object *) self)->type;
431 volatile struct gdb_exception except;
433 TRY_CATCH (except, RETURN_MASK_ALL)
435 check_typedef (type);
437 /* Ignore exceptions. */
439 return PyLong_FromLong (TYPE_LENGTH (type));
443 typy_lookup_typename (char *type_name, struct block *block)
445 struct type *type = NULL;
446 volatile struct gdb_exception except;
448 TRY_CATCH (except, RETURN_MASK_ALL)
450 if (!strncmp (type_name, "struct ", 7))
451 type = lookup_struct (type_name + 7, NULL);
452 else if (!strncmp (type_name, "union ", 6))
453 type = lookup_union (type_name + 6, NULL);
454 else if (!strncmp (type_name, "enum ", 5))
455 type = lookup_enum (type_name + 5, NULL);
457 type = lookup_typename (python_language, python_gdbarch,
458 type_name, block, 0);
460 if (except.reason < 0)
462 PyErr_Format (except.reason == RETURN_QUIT
463 ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
464 "%s", except.message);
472 typy_lookup_type (struct demangle_component *demangled,
477 enum demangle_component_type demangled_type;
479 /* Save the type: typy_lookup_type() may (indirectly) overwrite
480 memory pointed by demangled. */
481 demangled_type = demangled->type;
483 if (demangled_type == DEMANGLE_COMPONENT_POINTER
484 || demangled_type == DEMANGLE_COMPONENT_REFERENCE
485 || demangled_type == DEMANGLE_COMPONENT_CONST
486 || demangled_type == DEMANGLE_COMPONENT_VOLATILE)
488 type = typy_lookup_type (demangled->u.s_binary.left, block);
492 switch (demangled_type)
494 case DEMANGLE_COMPONENT_REFERENCE:
495 return lookup_reference_type (type);
496 case DEMANGLE_COMPONENT_POINTER:
497 return lookup_pointer_type (type);
498 case DEMANGLE_COMPONENT_CONST:
499 return make_cv_type (1, 0, type, NULL);
500 case DEMANGLE_COMPONENT_VOLATILE:
501 return make_cv_type (0, 1, type, NULL);
505 type_name = cp_comp_to_string (demangled, 10);
506 type = typy_lookup_typename (type_name, block);
513 typy_template_argument (PyObject *self, PyObject *args)
516 struct type *type = ((type_object *) self)->type;
517 struct demangle_component *demangled;
519 struct type *argtype;
520 struct block *block = NULL;
521 PyObject *block_obj = NULL;
523 if (! PyArg_ParseTuple (args, "i|O", &argno, &block_obj))
528 block = block_object_to_block (block_obj);
531 PyErr_SetString (PyExc_RuntimeError,
532 _("Second argument must be block."));
537 type = check_typedef (type);
538 if (TYPE_CODE (type) == TYPE_CODE_REF)
539 type = check_typedef (TYPE_TARGET_TYPE (type));
541 if (TYPE_NAME (type) == NULL)
543 PyErr_SetString (PyExc_RuntimeError, _("Null type name."));
547 /* Note -- this is not thread-safe. */
548 demangled = cp_demangled_name_to_comp (TYPE_NAME (type), &err);
551 PyErr_SetString (PyExc_RuntimeError, err);
555 /* Strip off component names. */
556 while (demangled->type == DEMANGLE_COMPONENT_QUAL_NAME
557 || demangled->type == DEMANGLE_COMPONENT_LOCAL_NAME)
558 demangled = demangled->u.s_binary.right;
560 if (demangled->type != DEMANGLE_COMPONENT_TEMPLATE)
562 PyErr_SetString (PyExc_RuntimeError, _("Type is not a template."));
566 /* Skip from the template to the arguments. */
567 demangled = demangled->u.s_binary.right;
569 for (i = 0; demangled && i < argno; ++i)
570 demangled = demangled->u.s_binary.right;
574 PyErr_Format (PyExc_RuntimeError, _("No argument %d in template."),
579 argtype = typy_lookup_type (demangled->u.s_binary.left, block);
583 return type_to_type_object (argtype);
587 typy_str (PyObject *self)
589 volatile struct gdb_exception except;
590 char *thetype = NULL;
594 TRY_CATCH (except, RETURN_MASK_ALL)
596 struct cleanup *old_chain;
599 stb = mem_fileopen ();
600 old_chain = make_cleanup_ui_file_delete (stb);
602 type_print (type_object_to_type (self), "", stb, -1);
604 thetype = ui_file_xstrdup (stb, &length);
605 do_cleanups (old_chain);
607 if (except.reason < 0)
610 GDB_PY_HANDLE_EXCEPTION (except);
613 result = PyUnicode_Decode (thetype, length, host_charset (), NULL);
621 static const struct objfile_data *typy_objfile_data_key;
624 save_objfile_types (struct objfile *objfile, void *datum)
626 type_object *obj = datum;
628 struct cleanup *cleanup;
630 /* This prevents another thread from freeing the objects we're
632 cleanup = ensure_python_env (get_objfile_arch (objfile), current_language);
634 copied_types = create_copied_types_hash (objfile);
638 type_object *next = obj->next;
640 htab_empty (copied_types);
642 obj->type = copy_type_recursive (objfile, obj->type, copied_types);
650 htab_delete (copied_types);
652 do_cleanups (cleanup);
656 set_type (type_object *obj, struct type *type)
660 if (type && TYPE_OBJFILE (type))
662 struct objfile *objfile = TYPE_OBJFILE (type);
664 obj->next = objfile_data (objfile, typy_objfile_data_key);
666 obj->next->prev = obj;
667 set_objfile_data (objfile, typy_objfile_data_key, obj);
674 typy_dealloc (PyObject *obj)
676 type_object *type = (type_object *) obj;
679 type->prev->next = type->next;
680 else if (type->type && TYPE_OBJFILE (type->type))
682 /* Must reset head of list. */
683 struct objfile *objfile = TYPE_OBJFILE (type->type);
686 set_objfile_data (objfile, typy_objfile_data_key, type->next);
689 type->next->prev = type->prev;
691 type->ob_type->tp_free (type);
694 /* Create a new Type referring to TYPE. */
696 type_to_type_object (struct type *type)
698 type_object *type_obj;
700 type_obj = PyObject_New (type_object, &type_object_type);
702 set_type (type_obj, type);
704 return (PyObject *) type_obj;
708 type_object_to_type (PyObject *obj)
710 if (! PyObject_TypeCheck (obj, &type_object_type))
712 return ((type_object *) obj)->type;
717 /* Implementation of gdb.lookup_type. */
719 gdbpy_lookup_type (PyObject *self, PyObject *args, PyObject *kw)
721 static char *keywords[] = { "name", "block", NULL };
722 char *type_name = NULL;
723 struct type *type = NULL;
724 PyObject *block_obj = NULL;
725 struct block *block = NULL;
727 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O", keywords,
728 &type_name, &block_obj))
733 block = block_object_to_block (block_obj);
736 PyErr_SetString (PyExc_RuntimeError,
737 _("'block' argument must be a Block."));
742 type = typy_lookup_typename (type_name, block);
746 return (PyObject *) type_to_type_object (type);
750 gdbpy_initialize_types (void)
754 typy_objfile_data_key
755 = register_objfile_data_with_cleanup (save_objfile_types, NULL);
757 if (PyType_Ready (&type_object_type) < 0)
759 if (PyType_Ready (&field_object_type) < 0)
762 for (i = 0; pyty_codes[i].name; ++i)
764 if (PyModule_AddIntConstant (gdb_module,
765 /* Cast needed for Python 2.4. */
766 (char *) pyty_codes[i].name,
767 pyty_codes[i].code) < 0)
771 Py_INCREF (&type_object_type);
772 PyModule_AddObject (gdb_module, "Type", (PyObject *) &type_object_type);
774 Py_INCREF (&field_object_type);
775 PyModule_AddObject (gdb_module, "Field", (PyObject *) &field_object_type);
780 static PyGetSetDef type_object_getset[] =
782 { "code", typy_get_code, NULL,
783 "The code for this type.", NULL },
784 { "sizeof", typy_get_sizeof, NULL,
785 "The size of this type, in bytes.", NULL },
786 { "tag", typy_get_tag, NULL,
787 "The tag name for this type, or None.", NULL },
791 static PyMethodDef type_object_methods[] =
793 { "const", typy_const, METH_NOARGS,
795 Return a const variant of this type." },
796 { "fields", typy_fields, METH_NOARGS,
798 Return a sequence holding all the fields of this type.\n\
799 Each field is a dictionary." },
800 { "pointer", typy_pointer, METH_NOARGS,
801 "pointer () -> Type\n\
802 Return a type of pointer to this type." },
803 { "range", typy_range, METH_NOARGS,
804 "range () -> tuple\n\
805 Return a tuple containing the lower and upper range for this type."},
806 { "reference", typy_reference, METH_NOARGS,
807 "reference () -> Type\n\
808 Return a type of reference to this type." },
809 { "strip_typedefs", typy_strip_typedefs, METH_NOARGS,
810 "strip_typedefs () -> Type\n\
811 Return a type formed by stripping this type of all typedefs."},
812 { "target", typy_target, METH_NOARGS,
813 "target () -> Type\n\
814 Return the target type of this type." },
815 { "template_argument", typy_template_argument, METH_VARARGS,
816 "template_argument (arg, [block]) -> Type\n\
817 Return the type of a template argument." },
818 { "unqualified", typy_unqualified, METH_NOARGS,
819 "unqualified () -> Type\n\
820 Return a variant of this type without const or volatile attributes." },
821 { "volatile", typy_volatile, METH_NOARGS,
822 "volatile () -> Type\n\
823 Return a volatile variant of this type" },
827 static PyTypeObject type_object_type =
829 PyObject_HEAD_INIT (NULL)
831 "gdb.Type", /*tp_name*/
832 sizeof (type_object), /*tp_basicsize*/
834 typy_dealloc, /*tp_dealloc*/
841 0, /*tp_as_sequence*/
849 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /*tp_flags*/
850 "GDB type object", /* tp_doc */
853 0, /* tp_richcompare */
854 0, /* tp_weaklistoffset */
857 type_object_methods, /* tp_methods */
859 type_object_getset, /* tp_getset */
862 0, /* tp_descr_get */
863 0, /* tp_descr_set */
864 0, /* tp_dictoffset */
870 static PyTypeObject field_object_type =
872 PyObject_HEAD_INIT (NULL)
874 "gdb.Field", /*tp_name*/
875 sizeof (field_object), /*tp_basicsize*/
877 field_dealloc, /*tp_dealloc*/
884 0, /*tp_as_sequence*/
892 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /*tp_flags*/
893 "GDB field object", /* tp_doc */
896 0, /* tp_richcompare */
897 0, /* tp_weaklistoffset */
905 0, /* tp_descr_get */
906 0, /* tp_descr_set */
907 offsetof (field_object, dict), /* tp_dictoffset */