1 /* Python interface to types.
3 Copyright (C) 2008-2022 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 "python-internal.h"
25 #include "cp-support.h"
29 #include "typeprint.h"
37 /* If a Type object is associated with an objfile, it is kept on a
38 doubly-linked list, rooted in the objfile. This lets us copy the
39 underlying struct type when the objfile is deleted. */
40 struct type_object *prev;
41 struct type_object *next;
44 extern PyTypeObject type_object_type
45 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("type_object");
52 /* Dictionary holding our attributes. */
56 extern PyTypeObject field_object_type
57 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("field_object");
59 /* A type iterator object. */
60 struct typy_iterator_object {
62 /* The current field index. */
65 enum gdbpy_iter_kind kind;
66 /* Pointer back to the original source type object. */
70 extern PyTypeObject type_iterator_object_type
71 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("typy_iterator_object");
73 /* This is used to initialize various gdb.TYPE_ constants. */
82 /* Forward declarations. */
83 static PyObject *typy_make_iter (PyObject *self, enum gdbpy_iter_kind kind);
85 #define ENTRY(X) { X, #X }
87 static struct pyty_code pyty_codes[] =
89 ENTRY (TYPE_CODE_BITSTRING),
90 ENTRY (TYPE_CODE_PTR),
91 ENTRY (TYPE_CODE_ARRAY),
92 ENTRY (TYPE_CODE_STRUCT),
93 ENTRY (TYPE_CODE_UNION),
94 ENTRY (TYPE_CODE_ENUM),
95 ENTRY (TYPE_CODE_FLAGS),
96 ENTRY (TYPE_CODE_FUNC),
97 ENTRY (TYPE_CODE_INT),
98 ENTRY (TYPE_CODE_FLT),
99 ENTRY (TYPE_CODE_VOID),
100 ENTRY (TYPE_CODE_SET),
101 ENTRY (TYPE_CODE_RANGE),
102 ENTRY (TYPE_CODE_STRING),
103 ENTRY (TYPE_CODE_ERROR),
104 ENTRY (TYPE_CODE_METHOD),
105 ENTRY (TYPE_CODE_METHODPTR),
106 ENTRY (TYPE_CODE_MEMBERPTR),
107 ENTRY (TYPE_CODE_REF),
108 ENTRY (TYPE_CODE_RVALUE_REF),
109 ENTRY (TYPE_CODE_CHAR),
110 ENTRY (TYPE_CODE_BOOL),
111 ENTRY (TYPE_CODE_COMPLEX),
112 ENTRY (TYPE_CODE_TYPEDEF),
113 ENTRY (TYPE_CODE_NAMESPACE),
114 ENTRY (TYPE_CODE_DECFLOAT),
115 ENTRY (TYPE_CODE_INTERNAL_FUNCTION),
121 field_dealloc (PyObject *obj)
123 field_object *f = (field_object *) obj;
125 Py_XDECREF (f->dict);
126 Py_TYPE (obj)->tp_free (obj);
132 gdbpy_ref<field_object> result (PyObject_New (field_object,
133 &field_object_type));
137 result->dict = PyDict_New ();
141 return (PyObject *) result.release ();
146 /* Return true if OBJ is of type gdb.Field, false otherwise. */
149 gdbpy_is_field (PyObject *obj)
151 return PyObject_TypeCheck (obj, &field_object_type);
154 /* Return the code for this type. */
156 typy_get_code (PyObject *self, void *closure)
158 struct type *type = ((type_object *) self)->type;
160 return gdb_py_object_from_longest (type->code ()).release ();
163 /* Helper function for typy_fields which converts a single field to a
164 gdb.Field object. Returns NULL on error. */
167 convert_field (struct type *type, int field)
169 gdbpy_ref<> result (field_new ());
174 gdbpy_ref<> arg (type_to_type_object (type));
177 if (PyObject_SetAttrString (result.get (), "parent_type", arg.get ()) < 0)
180 if (!field_is_static (&type->field (field)))
182 const char *attrstring;
184 if (type->code () == TYPE_CODE_ENUM)
186 arg = gdb_py_object_from_longest (type->field (field).loc_enumval ());
187 attrstring = "enumval";
191 if (type->field (field).loc_kind () == FIELD_LOC_KIND_DWARF_BLOCK)
192 arg = gdbpy_ref<>::new_reference (Py_None);
194 arg = gdb_py_object_from_longest (type->field (field).loc_bitpos ());
195 attrstring = "bitpos";
201 if (PyObject_SetAttrString (result.get (), attrstring, arg.get ()) < 0)
206 if (type->field (field).name ())
208 const char *field_name = type->field (field).name ();
210 if (field_name[0] != '\0')
212 arg.reset (PyUnicode_FromString (type->field (field).name ()));
218 arg = gdbpy_ref<>::new_reference (Py_None);
220 if (PyObject_SetAttrString (result.get (), "name", arg.get ()) < 0)
223 arg = gdbpy_ref<>::new_reference (TYPE_FIELD_ARTIFICIAL (type, field)
224 ? Py_True : Py_False);
225 if (PyObject_SetAttrString (result.get (), "artificial", arg.get ()) < 0)
228 if (type->code () == TYPE_CODE_STRUCT)
229 arg = gdbpy_ref<>::new_reference (field < TYPE_N_BASECLASSES (type)
230 ? Py_True : Py_False);
232 arg = gdbpy_ref<>::new_reference (Py_False);
233 if (PyObject_SetAttrString (result.get (), "is_base_class", arg.get ()) < 0)
236 arg = gdb_py_object_from_longest (TYPE_FIELD_BITSIZE (type, field));
239 if (PyObject_SetAttrString (result.get (), "bitsize", arg.get ()) < 0)
242 /* A field can have a NULL type in some situations. */
243 if (type->field (field).type () == NULL)
244 arg = gdbpy_ref<>::new_reference (Py_None);
246 arg.reset (type_to_type_object (type->field (field).type ()));
249 if (PyObject_SetAttrString (result.get (), "type", arg.get ()) < 0)
255 /* Helper function to return the name of a field, as a gdb.Field object.
256 If the field doesn't have a name, None is returned. */
259 field_name (struct type *type, int field)
263 if (type->field (field).name ())
264 result.reset (PyUnicode_FromString (type->field (field).name ()));
266 result = gdbpy_ref<>::new_reference (Py_None);
271 /* Helper function for Type standard mapping methods. Returns a
272 Python object for field i of the type. "kind" specifies what to
273 return: the name of the field, a gdb.Field object corresponding to
274 the field, or a tuple consisting of field name and gdb.Field
278 make_fielditem (struct type *type, int i, enum gdbpy_iter_kind kind)
284 gdbpy_ref<> key (field_name (type, i));
287 gdbpy_ref<> value = convert_field (type, i);
290 gdbpy_ref<> item (PyTuple_New (2));
293 PyTuple_SET_ITEM (item.get (), 0, key.release ());
294 PyTuple_SET_ITEM (item.get (), 1, value.release ());
298 return field_name (type, i);
300 return convert_field (type, i);
302 gdb_assert_not_reached ("invalid gdbpy_iter_kind");
305 /* Return a sequence of all field names, fields, or (name, field) pairs.
306 Each field is a gdb.Field object. */
309 typy_fields_items (PyObject *self, enum gdbpy_iter_kind kind)
311 PyObject *py_type = self;
312 struct type *type = ((type_object *) py_type)->type;
313 struct type *checked_type = type;
317 checked_type = check_typedef (checked_type);
319 catch (const gdb_exception &except)
321 GDB_PY_HANDLE_EXCEPTION (except);
324 gdbpy_ref<> type_holder;
325 if (checked_type != type)
327 type_holder.reset (type_to_type_object (checked_type));
328 if (type_holder == nullptr)
330 py_type = type_holder.get ();
332 gdbpy_ref<> iter (typy_make_iter (py_type, kind));
336 return PySequence_List (iter.get ());
339 /* Return a sequence of all fields. Each field is a gdb.Field object. */
342 typy_values (PyObject *self, PyObject *args)
344 return typy_fields_items (self, iter_values);
347 /* Return a sequence of all fields. Each field is a gdb.Field object.
348 This method is similar to typy_values, except where the supplied
349 gdb.Type is an array, in which case it returns a list of one entry
350 which is a gdb.Field object for a range (the array bounds). */
353 typy_fields (PyObject *self, PyObject *args)
355 struct type *type = ((type_object *) self)->type;
357 if (type->code () != TYPE_CODE_ARRAY)
358 return typy_fields_items (self, iter_values);
360 /* Array type. Handle this as a special case because the common
361 machinery wants struct or union or enum types. Build a list of
362 one entry which is the range for the array. */
363 gdbpy_ref<> r = convert_field (type, 0);
367 return Py_BuildValue ("[O]", r.get ());
370 /* Return a sequence of all field names. Each field is a gdb.Field object. */
373 typy_field_names (PyObject *self, PyObject *args)
375 return typy_fields_items (self, iter_keys);
378 /* Return a sequence of all (name, fields) pairs. Each field is a
382 typy_items (PyObject *self, PyObject *args)
384 return typy_fields_items (self, iter_items);
387 /* Return the type's name, or None. */
390 typy_get_name (PyObject *self, void *closure)
392 struct type *type = ((type_object *) self)->type;
394 if (type->name () == NULL)
396 /* Ada type names are encoded, but it is better for users to see the
398 if (ADA_TYPE_P (type))
400 std::string name = ada_decode (type->name (), false);
402 return PyUnicode_FromString (name.c_str ());
404 return PyUnicode_FromString (type->name ());
407 /* Return the type's tag, or None. */
409 typy_get_tag (PyObject *self, void *closure)
411 struct type *type = ((type_object *) self)->type;
412 const char *tagname = nullptr;
414 if (type->code () == TYPE_CODE_STRUCT
415 || type->code () == TYPE_CODE_UNION
416 || type->code () == TYPE_CODE_ENUM)
417 tagname = type->name ();
419 if (tagname == nullptr)
421 return PyUnicode_FromString (tagname);
424 /* Return the type's objfile, or None. */
426 typy_get_objfile (PyObject *self, void *closure)
428 struct type *type = ((type_object *) self)->type;
429 struct objfile *objfile = type->objfile_owner ();
431 if (objfile == nullptr)
433 return objfile_to_objfile_object (objfile).release ();
436 /* Return true if this is a scalar type, otherwise, returns false. */
439 typy_is_scalar (PyObject *self, void *closure)
441 struct type *type = ((type_object *) self)->type;
443 if (is_scalar_type (type))
449 /* Return true if this type is signed. Raises a ValueError if this type
450 is not a scalar type. */
453 typy_is_signed (PyObject *self, void *closure)
455 struct type *type = ((type_object *) self)->type;
457 if (!is_scalar_type (type))
459 PyErr_SetString (PyExc_ValueError,
460 _("Type must be a scalar type"));
464 if (type->is_unsigned ())
470 /* Return the type, stripped of typedefs. */
472 typy_strip_typedefs (PyObject *self, PyObject *args)
474 struct type *type = ((type_object *) self)->type;
478 type = check_typedef (type);
480 catch (const gdb_exception &except)
482 GDB_PY_HANDLE_EXCEPTION (except);
485 return type_to_type_object (type);
488 /* Strip typedefs and pointers/reference from a type. Then check that
489 it is a struct, union, or enum type. If not, raise TypeError. */
492 typy_get_composite (struct type *type)
499 type = check_typedef (type);
501 catch (const gdb_exception &except)
503 GDB_PY_HANDLE_EXCEPTION (except);
506 if (!type->is_pointer_or_reference ())
508 type = TYPE_TARGET_TYPE (type);
511 /* If this is not a struct, union, or enum type, raise TypeError
513 if (type->code () != TYPE_CODE_STRUCT
514 && type->code () != TYPE_CODE_UNION
515 && type->code () != TYPE_CODE_ENUM
516 && type->code () != TYPE_CODE_METHOD
517 && type->code () != TYPE_CODE_FUNC)
519 PyErr_SetString (PyExc_TypeError,
520 "Type is not a structure, union, enum, or function type.");
527 /* Helper for typy_array and typy_vector. */
530 typy_array_1 (PyObject *self, PyObject *args, int is_vector)
533 PyObject *n2_obj = NULL;
534 struct type *array = NULL;
535 struct type *type = ((type_object *) self)->type;
537 if (! PyArg_ParseTuple (args, "l|O", &n1, &n2_obj))
542 if (!PyLong_Check (n2_obj))
544 PyErr_SetString (PyExc_RuntimeError,
545 _("Array bound must be an integer"));
549 if (! gdb_py_int_as_long (n2_obj, &n2))
558 if (n2 < n1 - 1) /* Note: An empty array has n2 == n1 - 1. */
560 PyErr_SetString (PyExc_ValueError,
561 _("Array length must not be negative"));
567 array = lookup_array_range_type (type, n1, n2);
569 make_vector_type (array);
571 catch (const gdb_exception &except)
573 GDB_PY_HANDLE_EXCEPTION (except);
576 return type_to_type_object (array);
579 /* Return an array type. */
582 typy_array (PyObject *self, PyObject *args)
584 return typy_array_1 (self, args, 0);
587 /* Return a vector type. */
590 typy_vector (PyObject *self, PyObject *args)
592 return typy_array_1 (self, args, 1);
595 /* Return a Type object which represents a pointer to SELF. */
597 typy_pointer (PyObject *self, PyObject *args)
599 struct type *type = ((type_object *) self)->type;
603 type = lookup_pointer_type (type);
605 catch (const gdb_exception &except)
607 GDB_PY_HANDLE_EXCEPTION (except);
610 return type_to_type_object (type);
613 /* Return the range of a type represented by SELF. The return type is
614 a tuple. The first element of the tuple contains the low bound,
615 while the second element of the tuple contains the high bound. */
617 typy_range (PyObject *self, PyObject *args)
619 struct type *type = ((type_object *) self)->type;
620 /* Initialize these to appease GCC warnings. */
621 LONGEST low = 0, high = 0;
623 if (type->code () != TYPE_CODE_ARRAY
624 && type->code () != TYPE_CODE_STRING
625 && type->code () != TYPE_CODE_RANGE)
627 PyErr_SetString (PyExc_RuntimeError,
628 _("This type does not have a range."));
632 switch (type->code ())
634 case TYPE_CODE_ARRAY:
635 case TYPE_CODE_STRING:
636 case TYPE_CODE_RANGE:
637 if (type->bounds ()->low.kind () == PROP_CONST)
638 low = type->bounds ()->low.const_val ();
642 if (type->bounds ()->high.kind () == PROP_CONST)
643 high = type->bounds ()->high.const_val ();
649 gdbpy_ref<> low_bound = gdb_py_object_from_longest (low);
650 if (low_bound == NULL)
653 gdbpy_ref<> high_bound = gdb_py_object_from_longest (high);
654 if (high_bound == NULL)
657 gdbpy_ref<> result (PyTuple_New (2));
661 if (PyTuple_SetItem (result.get (), 0, low_bound.release ()) != 0
662 || PyTuple_SetItem (result.get (), 1, high_bound.release ()) != 0)
664 return result.release ();
667 /* Return a Type object which represents a reference to SELF. */
669 typy_reference (PyObject *self, PyObject *args)
671 struct type *type = ((type_object *) self)->type;
675 type = lookup_lvalue_reference_type (type);
677 catch (const gdb_exception &except)
679 GDB_PY_HANDLE_EXCEPTION (except);
682 return type_to_type_object (type);
685 /* Return a Type object which represents the target type of SELF. */
687 typy_target (PyObject *self, PyObject *args)
689 struct type *type = ((type_object *) self)->type;
691 if (!TYPE_TARGET_TYPE (type))
693 PyErr_SetString (PyExc_RuntimeError,
694 _("Type does not have a target."));
698 return type_to_type_object (TYPE_TARGET_TYPE (type));
701 /* Return a const-qualified type variant. */
703 typy_const (PyObject *self, PyObject *args)
705 struct type *type = ((type_object *) self)->type;
709 type = make_cv_type (1, 0, type, NULL);
711 catch (const gdb_exception &except)
713 GDB_PY_HANDLE_EXCEPTION (except);
716 return type_to_type_object (type);
719 /* Return a volatile-qualified type variant. */
721 typy_volatile (PyObject *self, PyObject *args)
723 struct type *type = ((type_object *) self)->type;
727 type = make_cv_type (0, 1, type, NULL);
729 catch (const gdb_exception &except)
731 GDB_PY_HANDLE_EXCEPTION (except);
734 return type_to_type_object (type);
737 /* Return an unqualified type variant. */
739 typy_unqualified (PyObject *self, PyObject *args)
741 struct type *type = ((type_object *) self)->type;
745 type = make_cv_type (0, 0, type, NULL);
747 catch (const gdb_exception &except)
749 GDB_PY_HANDLE_EXCEPTION (except);
752 return type_to_type_object (type);
755 /* Return the size of the type represented by SELF, in bytes. */
757 typy_get_sizeof (PyObject *self, void *closure)
759 struct type *type = ((type_object *) self)->type;
761 bool size_varies = false;
764 check_typedef (type);
766 size_varies = TYPE_HAS_DYNAMIC_LENGTH (type);
768 catch (const gdb_exception &except)
772 /* Ignore exceptions. */
776 return gdb_py_object_from_longest (TYPE_LENGTH (type)).release ();
779 /* Return the alignment of the type represented by SELF, in bytes. */
781 typy_get_alignof (PyObject *self, void *closure)
783 struct type *type = ((type_object *) self)->type;
788 align = type_align (type);
790 catch (const gdb_exception &except)
795 /* Ignore exceptions. */
797 return gdb_py_object_from_ulongest (align).release ();
800 /* Return whether or not the type is dynamic. */
802 typy_get_dynamic (PyObject *self, void *closure)
804 struct type *type = ((type_object *) self)->type;
809 result = is_dynamic_type (type);
811 catch (const gdb_exception &except)
813 /* Ignore exceptions. */
822 typy_lookup_typename (const char *type_name, const struct block *block)
824 struct type *type = NULL;
828 if (startswith (type_name, "struct "))
829 type = lookup_struct (type_name + 7, NULL);
830 else if (startswith (type_name, "union "))
831 type = lookup_union (type_name + 6, NULL);
832 else if (startswith (type_name, "enum "))
833 type = lookup_enum (type_name + 5, NULL);
835 type = lookup_typename (current_language,
836 type_name, block, 0);
838 catch (const gdb_exception &except)
840 GDB_PY_HANDLE_EXCEPTION (except);
847 typy_lookup_type (struct demangle_component *demangled,
848 const struct block *block)
850 struct type *type, *rtype = NULL;
851 enum demangle_component_type demangled_type;
853 /* Save the type: typy_lookup_type() may (indirectly) overwrite
854 memory pointed by demangled. */
855 demangled_type = demangled->type;
857 if (demangled_type == DEMANGLE_COMPONENT_POINTER
858 || demangled_type == DEMANGLE_COMPONENT_REFERENCE
859 || demangled_type == DEMANGLE_COMPONENT_RVALUE_REFERENCE
860 || demangled_type == DEMANGLE_COMPONENT_CONST
861 || demangled_type == DEMANGLE_COMPONENT_VOLATILE)
863 type = typy_lookup_type (demangled->u.s_binary.left, block);
869 /* If the demangled_type matches with one of the types
870 below, run the corresponding function and save the type
871 to return later. We cannot just return here as we are in
872 an exception handler. */
873 switch (demangled_type)
875 case DEMANGLE_COMPONENT_REFERENCE:
876 rtype = lookup_lvalue_reference_type (type);
878 case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
879 rtype = lookup_rvalue_reference_type (type);
881 case DEMANGLE_COMPONENT_POINTER:
882 rtype = lookup_pointer_type (type);
884 case DEMANGLE_COMPONENT_CONST:
885 rtype = make_cv_type (1, 0, type, NULL);
887 case DEMANGLE_COMPONENT_VOLATILE:
888 rtype = make_cv_type (0, 1, type, NULL);
892 catch (const gdb_exception &except)
894 GDB_PY_HANDLE_EXCEPTION (except);
898 /* If we have a type from the switch statement above, just return
903 /* We don't have a type, so lookup the type. */
904 gdb::unique_xmalloc_ptr<char> type_name = cp_comp_to_string (demangled, 10);
905 return typy_lookup_typename (type_name.get (), block);
908 /* This is a helper function for typy_template_argument that is used
909 when the type does not have template symbols attached. It works by
910 parsing the type name. This happens with compilers, like older
911 versions of GCC, that do not emit DW_TAG_template_*. */
914 typy_legacy_template_argument (struct type *type, const struct block *block,
918 struct demangle_component *demangled;
919 std::unique_ptr<demangle_parse_info> info;
921 struct type *argtype;
923 if (type->name () == NULL)
925 PyErr_SetString (PyExc_RuntimeError, _("Null type name."));
931 /* Note -- this is not thread-safe. */
932 info = cp_demangled_name_to_comp (type->name (), &err);
934 catch (const gdb_exception &except)
936 GDB_PY_HANDLE_EXCEPTION (except);
941 PyErr_SetString (PyExc_RuntimeError, err.c_str ());
944 demangled = info->tree;
946 /* Strip off component names. */
947 while (demangled->type == DEMANGLE_COMPONENT_QUAL_NAME
948 || demangled->type == DEMANGLE_COMPONENT_LOCAL_NAME)
949 demangled = demangled->u.s_binary.right;
951 if (demangled->type != DEMANGLE_COMPONENT_TEMPLATE)
953 PyErr_SetString (PyExc_RuntimeError, _("Type is not a template."));
957 /* Skip from the template to the arguments. */
958 demangled = demangled->u.s_binary.right;
960 for (i = 0; demangled && i < argno; ++i)
961 demangled = demangled->u.s_binary.right;
965 PyErr_Format (PyExc_RuntimeError, _("No argument %d in template."),
970 argtype = typy_lookup_type (demangled->u.s_binary.left, block);
974 return type_to_type_object (argtype);
978 typy_template_argument (PyObject *self, PyObject *args)
981 struct type *type = ((type_object *) self)->type;
982 const struct block *block = NULL;
983 PyObject *block_obj = NULL;
985 struct value *val = NULL;
987 if (! PyArg_ParseTuple (args, "i|O", &argno, &block_obj))
992 PyErr_SetString (PyExc_RuntimeError,
993 _("Template argument number must be non-negative"));
999 block = block_object_to_block (block_obj);
1002 PyErr_SetString (PyExc_RuntimeError,
1003 _("Second argument must be block."));
1010 type = check_typedef (type);
1011 if (TYPE_IS_REFERENCE (type))
1012 type = check_typedef (TYPE_TARGET_TYPE (type));
1014 catch (const gdb_exception &except)
1016 GDB_PY_HANDLE_EXCEPTION (except);
1019 /* We might not have DW_TAG_template_*, so try to parse the type's
1020 name. This is inefficient if we do not have a template type --
1021 but that is going to wind up as an error anyhow. */
1022 if (! TYPE_N_TEMPLATE_ARGUMENTS (type))
1023 return typy_legacy_template_argument (type, block, argno);
1025 if (argno >= TYPE_N_TEMPLATE_ARGUMENTS (type))
1027 PyErr_Format (PyExc_RuntimeError, _("No argument %d in template."),
1032 sym = TYPE_TEMPLATE_ARGUMENT (type, argno);
1033 if (sym->aclass () == LOC_TYPEDEF)
1034 return type_to_type_object (sym->type ());
1035 else if (sym->aclass () == LOC_OPTIMIZED_OUT)
1037 PyErr_Format (PyExc_RuntimeError,
1038 _("Template argument is optimized out"));
1044 val = value_of_variable (sym, block);
1046 catch (const gdb_exception &except)
1048 GDB_PY_HANDLE_EXCEPTION (except);
1051 return value_to_value_object (val);
1055 typy_str (PyObject *self)
1057 string_file thetype;
1061 current_language->print_type (type_object_to_type (self), "",
1063 &type_print_raw_options);
1065 catch (const gdb_exception &except)
1067 GDB_PY_HANDLE_EXCEPTION (except);
1070 return PyUnicode_Decode (thetype.c_str (), thetype.size (),
1071 host_charset (), NULL);
1074 /* Implement the richcompare method. */
1077 typy_richcompare (PyObject *self, PyObject *other, int op)
1079 bool result = false;
1080 struct type *type1 = type_object_to_type (self);
1081 struct type *type2 = type_object_to_type (other);
1083 /* We can only compare ourselves to another Type object, and only
1084 for equality or inequality. */
1085 if (type2 == NULL || (op != Py_EQ && op != Py_NE))
1087 Py_INCREF (Py_NotImplemented);
1088 return Py_NotImplemented;
1097 result = types_deeply_equal (type1, type2);
1099 catch (const gdb_exception &except)
1101 /* If there is a GDB exception, a comparison is not capable
1102 (or trusted), so exit. */
1103 GDB_PY_HANDLE_EXCEPTION (except);
1107 if (op == (result ? Py_EQ : Py_NE))
1114 static const struct objfile_data *typy_objfile_data_key;
1117 save_objfile_types (struct objfile *objfile, void *datum)
1119 type_object *obj = (type_object *) datum;
1121 if (!gdb_python_initialized)
1124 /* This prevents another thread from freeing the objects we're
1126 gdbpy_enter enter_py (objfile->arch ());
1128 htab_up copied_types = create_copied_types_hash (objfile);
1132 type_object *next = obj->next;
1134 htab_empty (copied_types.get ());
1136 obj->type = copy_type_recursive (objfile, obj->type,
1137 copied_types.get ());
1147 set_type (type_object *obj, struct type *type)
1151 if (type != nullptr && type->objfile_owner () != nullptr)
1153 struct objfile *objfile = type->objfile_owner ();
1155 obj->next = ((type_object *)
1156 objfile_data (objfile, typy_objfile_data_key));
1158 obj->next->prev = obj;
1159 set_objfile_data (objfile, typy_objfile_data_key, obj);
1166 typy_dealloc (PyObject *obj)
1168 type_object *type = (type_object *) obj;
1171 type->prev->next = type->next;
1172 else if (type->type != nullptr && type->type->objfile_owner () != nullptr)
1174 /* Must reset head of list. */
1175 struct objfile *objfile = type->type->objfile_owner ();
1178 set_objfile_data (objfile, typy_objfile_data_key, type->next);
1181 type->next->prev = type->prev;
1183 Py_TYPE (type)->tp_free (type);
1186 /* Return number of fields ("length" of the field dictionary). */
1189 typy_length (PyObject *self)
1191 struct type *type = ((type_object *) self)->type;
1193 type = typy_get_composite (type);
1197 return type->num_fields ();
1200 /* Implements boolean evaluation of gdb.Type. Handle this like other
1201 Python objects that don't have a meaningful truth value -- all
1205 typy_nonzero (PyObject *self)
1210 /* Return optimized out value of this type. */
1213 typy_optimized_out (PyObject *self, PyObject *args)
1215 struct type *type = ((type_object *) self)->type;
1217 return value_to_value_object (allocate_optimized_out_value (type));
1220 /* Return a gdb.Field object for the field named by the argument. */
1223 typy_getitem (PyObject *self, PyObject *key)
1225 struct type *type = ((type_object *) self)->type;
1228 gdb::unique_xmalloc_ptr<char> field = python_string_to_host_string (key);
1232 /* We want just fields of this type, not of base types, so instead of
1233 using lookup_struct_elt_type, portions of that function are
1236 type = typy_get_composite (type);
1240 for (i = 0; i < type->num_fields (); i++)
1242 const char *t_field_name = type->field (i).name ();
1244 if (t_field_name && (strcmp_iw (t_field_name, field.get ()) == 0))
1245 return convert_field (type, i).release ();
1247 PyErr_SetObject (PyExc_KeyError, key);
1251 /* Implement the "get" method on the type object. This is the
1252 same as getitem if the key is present, but returns the supplied
1253 default value or None if the key is not found. */
1256 typy_get (PyObject *self, PyObject *args)
1258 PyObject *key, *defval = Py_None, *result;
1260 if (!PyArg_UnpackTuple (args, "get", 1, 2, &key, &defval))
1263 result = typy_getitem (self, key);
1267 /* typy_getitem returned error status. If the exception is
1268 KeyError, clear the exception status and return the defval
1269 instead. Otherwise return the exception unchanged. */
1270 if (!PyErr_ExceptionMatches (PyExc_KeyError))
1278 /* Implement the "has_key" method on the type object. */
1281 typy_has_key (PyObject *self, PyObject *args)
1283 struct type *type = ((type_object *) self)->type;
1287 if (!PyArg_ParseTuple (args, "s", &field))
1290 /* We want just fields of this type, not of base types, so instead of
1291 using lookup_struct_elt_type, portions of that function are
1294 type = typy_get_composite (type);
1298 for (i = 0; i < type->num_fields (); i++)
1300 const char *t_field_name = type->field (i).name ();
1302 if (t_field_name && (strcmp_iw (t_field_name, field) == 0))
1308 /* Make an iterator object to iterate over keys, values, or items. */
1311 typy_make_iter (PyObject *self, enum gdbpy_iter_kind kind)
1313 typy_iterator_object *typy_iter_obj;
1315 /* Check that "self" is a structure or union type. */
1316 if (typy_get_composite (((type_object *) self)->type) == NULL)
1319 typy_iter_obj = PyObject_New (typy_iterator_object,
1320 &type_iterator_object_type);
1321 if (typy_iter_obj == NULL)
1324 typy_iter_obj->field = 0;
1325 typy_iter_obj->kind = kind;
1327 typy_iter_obj->source = (type_object *) self;
1329 return (PyObject *) typy_iter_obj;
1332 /* iteritems() method. */
1335 typy_iteritems (PyObject *self, PyObject *args)
1337 return typy_make_iter (self, iter_items);
1340 /* iterkeys() method. */
1343 typy_iterkeys (PyObject *self, PyObject *args)
1345 return typy_make_iter (self, iter_keys);
1348 /* Iterating over the class, same as iterkeys except for the function
1352 typy_iter (PyObject *self)
1354 return typy_make_iter (self, iter_keys);
1357 /* itervalues() method. */
1360 typy_itervalues (PyObject *self, PyObject *args)
1362 return typy_make_iter (self, iter_values);
1365 /* Return a reference to the type iterator. */
1368 typy_iterator_iter (PyObject *self)
1374 /* Return the next field in the iteration through the list of fields
1378 typy_iterator_iternext (PyObject *self)
1380 typy_iterator_object *iter_obj = (typy_iterator_object *) self;
1381 struct type *type = iter_obj->source->type;
1383 if (iter_obj->field < type->num_fields ())
1385 gdbpy_ref<> result = make_fielditem (type, iter_obj->field,
1389 return result.release ();
1396 typy_iterator_dealloc (PyObject *obj)
1398 typy_iterator_object *iter_obj = (typy_iterator_object *) obj;
1400 Py_DECREF (iter_obj->source);
1401 Py_TYPE (obj)->tp_free (obj);
1404 /* Create a new Type referring to TYPE. */
1406 type_to_type_object (struct type *type)
1408 type_object *type_obj;
1412 /* Try not to let stub types leak out to Python. */
1413 if (type->is_stub ())
1414 type = check_typedef (type);
1418 /* Just ignore failures in check_typedef. */
1421 type_obj = PyObject_New (type_object, &type_object_type);
1423 set_type (type_obj, type);
1425 return (PyObject *) type_obj;
1429 type_object_to_type (PyObject *obj)
1431 if (! PyObject_TypeCheck (obj, &type_object_type))
1433 return ((type_object *) obj)->type;
1438 /* Implementation of gdb.lookup_type. */
1440 gdbpy_lookup_type (PyObject *self, PyObject *args, PyObject *kw)
1442 static const char *keywords[] = { "name", "block", NULL };
1443 const char *type_name = NULL;
1444 struct type *type = NULL;
1445 PyObject *block_obj = NULL;
1446 const struct block *block = NULL;
1448 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O", keywords,
1449 &type_name, &block_obj))
1454 block = block_object_to_block (block_obj);
1457 PyErr_SetString (PyExc_RuntimeError,
1458 _("'block' argument must be a Block."));
1463 type = typy_lookup_typename (type_name, block);
1467 return type_to_type_object (type);
1470 void _initialize_py_type ();
1472 _initialize_py_type ()
1474 typy_objfile_data_key
1475 = register_objfile_data_with_cleanup (save_objfile_types, NULL);
1479 gdbpy_initialize_types (void)
1481 if (PyType_Ready (&type_object_type) < 0)
1483 if (PyType_Ready (&field_object_type) < 0)
1485 if (PyType_Ready (&type_iterator_object_type) < 0)
1488 for (const auto &item : pyty_codes)
1490 if (PyModule_AddIntConstant (gdb_module, item.name, item.code) < 0)
1494 if (gdb_pymodule_addobject (gdb_module, "Type",
1495 (PyObject *) &type_object_type) < 0)
1498 if (gdb_pymodule_addobject (gdb_module, "TypeIterator",
1499 (PyObject *) &type_iterator_object_type) < 0)
1502 return gdb_pymodule_addobject (gdb_module, "Field",
1503 (PyObject *) &field_object_type);
1508 static gdb_PyGetSetDef type_object_getset[] =
1510 { "alignof", typy_get_alignof, NULL,
1511 "The alignment of this type, in bytes.", NULL },
1512 { "code", typy_get_code, NULL,
1513 "The code for this type.", NULL },
1514 { "dynamic", typy_get_dynamic, NULL,
1515 "Whether this type is dynamic.", NULL },
1516 { "name", typy_get_name, NULL,
1517 "The name for this type, or None.", NULL },
1518 { "sizeof", typy_get_sizeof, NULL,
1519 "The size of this type, in bytes.", NULL },
1520 { "tag", typy_get_tag, NULL,
1521 "The tag name for this type, or None.", NULL },
1522 { "objfile", typy_get_objfile, NULL,
1523 "The objfile this type was defined in, or None.", NULL },
1524 { "is_scalar", typy_is_scalar, nullptr,
1525 "Is this a scalar type?", nullptr },
1526 { "is_signed", typy_is_signed, nullptr,
1527 "Is this an signed type?", nullptr },
1531 static PyMethodDef type_object_methods[] =
1533 { "array", typy_array, METH_VARARGS,
1534 "array ([LOW_BOUND,] HIGH_BOUND) -> Type\n\
1535 Return a type which represents an array of objects of this type.\n\
1536 The bounds of the array are [LOW_BOUND, HIGH_BOUND] inclusive.\n\
1537 If LOW_BOUND is omitted, a value of zero is used." },
1538 { "vector", typy_vector, METH_VARARGS,
1539 "vector ([LOW_BOUND,] HIGH_BOUND) -> Type\n\
1540 Return a type which represents a vector of objects of this type.\n\
1541 The bounds of the array are [LOW_BOUND, HIGH_BOUND] inclusive.\n\
1542 If LOW_BOUND is omitted, a value of zero is used.\n\
1543 Vectors differ from arrays in that if the current language has C-style\n\
1544 arrays, vectors don't decay to a pointer to the first element.\n\
1545 They are first class values." },
1546 { "__contains__", typy_has_key, METH_VARARGS,
1547 "T.__contains__(k) -> True if T has a field named k, else False" },
1548 { "const", typy_const, METH_NOARGS,
1549 "const () -> Type\n\
1550 Return a const variant of this type." },
1551 { "optimized_out", typy_optimized_out, METH_NOARGS,
1552 "optimized_out() -> Value\n\
1553 Return optimized out value of this type." },
1554 { "fields", typy_fields, METH_NOARGS,
1555 "fields () -> list\n\
1556 Return a list holding all the fields of this type.\n\
1557 Each field is a gdb.Field object." },
1558 { "get", typy_get, METH_VARARGS,
1559 "T.get(k[,default]) -> returns field named k in T, if it exists;\n\
1560 otherwise returns default, if supplied, or None if not." },
1561 { "has_key", typy_has_key, METH_VARARGS,
1562 "T.has_key(k) -> True if T has a field named k, else False" },
1563 { "items", typy_items, METH_NOARGS,
1564 "items () -> list\n\
1565 Return a list of (name, field) pairs of this type.\n\
1566 Each field is a gdb.Field object." },
1567 { "iteritems", typy_iteritems, METH_NOARGS,
1568 "iteritems () -> an iterator over the (name, field)\n\
1569 pairs of this type. Each field is a gdb.Field object." },
1570 { "iterkeys", typy_iterkeys, METH_NOARGS,
1571 "iterkeys () -> an iterator over the field names of this type." },
1572 { "itervalues", typy_itervalues, METH_NOARGS,
1573 "itervalues () -> an iterator over the fields of this type.\n\
1574 Each field is a gdb.Field object." },
1575 { "keys", typy_field_names, METH_NOARGS,
1577 Return a list holding all the fields names of this type." },
1578 { "pointer", typy_pointer, METH_NOARGS,
1579 "pointer () -> Type\n\
1580 Return a type of pointer to this type." },
1581 { "range", typy_range, METH_NOARGS,
1582 "range () -> tuple\n\
1583 Return a tuple containing the lower and upper range for this type."},
1584 { "reference", typy_reference, METH_NOARGS,
1585 "reference () -> Type\n\
1586 Return a type of reference to this type." },
1587 { "strip_typedefs", typy_strip_typedefs, METH_NOARGS,
1588 "strip_typedefs () -> Type\n\
1589 Return a type formed by stripping this type of all typedefs."},
1590 { "target", typy_target, METH_NOARGS,
1591 "target () -> Type\n\
1592 Return the target type of this type." },
1593 { "template_argument", typy_template_argument, METH_VARARGS,
1594 "template_argument (arg, [block]) -> Type\n\
1595 Return the type of a template argument." },
1596 { "unqualified", typy_unqualified, METH_NOARGS,
1597 "unqualified () -> Type\n\
1598 Return a variant of this type without const or volatile attributes." },
1599 { "values", typy_values, METH_NOARGS,
1600 "values () -> list\n\
1601 Return a list holding all the fields of this type.\n\
1602 Each field is a gdb.Field object." },
1603 { "volatile", typy_volatile, METH_NOARGS,
1604 "volatile () -> Type\n\
1605 Return a volatile variant of this type" },
1609 static PyNumberMethods type_object_as_number = {
1611 NULL, /* nb_subtract */
1612 NULL, /* nb_multiply */
1613 NULL, /* nb_remainder */
1614 NULL, /* nb_divmod */
1615 NULL, /* nb_power */
1616 NULL, /* nb_negative */
1617 NULL, /* nb_positive */
1618 NULL, /* nb_absolute */
1619 typy_nonzero, /* nb_nonzero */
1620 NULL, /* nb_invert */
1621 NULL, /* nb_lshift */
1622 NULL, /* nb_rshift */
1627 NULL, /* reserved */
1628 NULL, /* nb_float */
1631 static PyMappingMethods typy_mapping = {
1634 NULL /* no "set" method */
1637 PyTypeObject type_object_type =
1639 PyVarObject_HEAD_INIT (NULL, 0)
1640 "gdb.Type", /*tp_name*/
1641 sizeof (type_object), /*tp_basicsize*/
1643 typy_dealloc, /*tp_dealloc*/
1649 &type_object_as_number, /*tp_as_number*/
1650 0, /*tp_as_sequence*/
1651 &typy_mapping, /*tp_as_mapping*/
1654 typy_str, /*tp_str*/
1658 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1659 "GDB type object", /* tp_doc */
1660 0, /* tp_traverse */
1662 typy_richcompare, /* tp_richcompare */
1663 0, /* tp_weaklistoffset */
1664 typy_iter, /* tp_iter */
1665 0, /* tp_iternext */
1666 type_object_methods, /* tp_methods */
1668 type_object_getset, /* tp_getset */
1671 0, /* tp_descr_get */
1672 0, /* tp_descr_set */
1673 0, /* tp_dictoffset */
1679 static gdb_PyGetSetDef field_object_getset[] =
1681 { "__dict__", gdb_py_generic_dict, NULL,
1682 "The __dict__ for this field.", &field_object_type },
1686 PyTypeObject field_object_type =
1688 PyVarObject_HEAD_INIT (NULL, 0)
1689 "gdb.Field", /*tp_name*/
1690 sizeof (field_object), /*tp_basicsize*/
1692 field_dealloc, /*tp_dealloc*/
1699 0, /*tp_as_sequence*/
1700 0, /*tp_as_mapping*/
1707 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1708 "GDB field object", /* tp_doc */
1709 0, /* tp_traverse */
1711 0, /* tp_richcompare */
1712 0, /* tp_weaklistoffset */
1714 0, /* tp_iternext */
1717 field_object_getset, /* tp_getset */
1720 0, /* tp_descr_get */
1721 0, /* tp_descr_set */
1722 offsetof (field_object, dict), /* tp_dictoffset */
1728 PyTypeObject type_iterator_object_type = {
1729 PyVarObject_HEAD_INIT (NULL, 0)
1730 "gdb.TypeIterator", /*tp_name*/
1731 sizeof (typy_iterator_object), /*tp_basicsize*/
1733 typy_iterator_dealloc, /*tp_dealloc*/
1740 0, /*tp_as_sequence*/
1741 0, /*tp_as_mapping*/
1748 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1749 "GDB type iterator object", /*tp_doc */
1752 0, /*tp_richcompare */
1753 0, /*tp_weaklistoffset */
1754 typy_iterator_iter, /*tp_iter */
1755 typy_iterator_iternext, /*tp_iternext */