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.reset (PyBool_FromLong (TYPE_FIELD_ARTIFICIAL (type, field)));
224 if (PyObject_SetAttrString (result.get (), "artificial", arg.get ()) < 0)
227 if (type->code () == TYPE_CODE_STRUCT)
228 arg.reset (PyBool_FromLong (field < TYPE_N_BASECLASSES (type)));
230 arg = gdbpy_ref<>::new_reference (Py_False);
231 if (PyObject_SetAttrString (result.get (), "is_base_class", arg.get ()) < 0)
234 arg = gdb_py_object_from_longest (TYPE_FIELD_BITSIZE (type, field));
237 if (PyObject_SetAttrString (result.get (), "bitsize", arg.get ()) < 0)
240 /* A field can have a NULL type in some situations. */
241 if (type->field (field).type () == NULL)
242 arg = gdbpy_ref<>::new_reference (Py_None);
244 arg.reset (type_to_type_object (type->field (field).type ()));
247 if (PyObject_SetAttrString (result.get (), "type", arg.get ()) < 0)
253 /* Helper function to return the name of a field, as a gdb.Field object.
254 If the field doesn't have a name, None is returned. */
257 field_name (struct type *type, int field)
261 if (type->field (field).name ())
262 result.reset (PyUnicode_FromString (type->field (field).name ()));
264 result = gdbpy_ref<>::new_reference (Py_None);
269 /* Helper function for Type standard mapping methods. Returns a
270 Python object for field i of the type. "kind" specifies what to
271 return: the name of the field, a gdb.Field object corresponding to
272 the field, or a tuple consisting of field name and gdb.Field
276 make_fielditem (struct type *type, int i, enum gdbpy_iter_kind kind)
282 gdbpy_ref<> key (field_name (type, i));
285 gdbpy_ref<> value = convert_field (type, i);
288 gdbpy_ref<> item (PyTuple_New (2));
291 PyTuple_SET_ITEM (item.get (), 0, key.release ());
292 PyTuple_SET_ITEM (item.get (), 1, value.release ());
296 return field_name (type, i);
298 return convert_field (type, i);
300 gdb_assert_not_reached ("invalid gdbpy_iter_kind");
303 /* Return a sequence of all field names, fields, or (name, field) pairs.
304 Each field is a gdb.Field object. */
307 typy_fields_items (PyObject *self, enum gdbpy_iter_kind kind)
309 PyObject *py_type = self;
310 struct type *type = ((type_object *) py_type)->type;
311 struct type *checked_type = type;
315 checked_type = check_typedef (checked_type);
317 catch (const gdb_exception &except)
319 GDB_PY_HANDLE_EXCEPTION (except);
322 gdbpy_ref<> type_holder;
323 if (checked_type != type)
325 type_holder.reset (type_to_type_object (checked_type));
326 if (type_holder == nullptr)
328 py_type = type_holder.get ();
330 gdbpy_ref<> iter (typy_make_iter (py_type, kind));
334 return PySequence_List (iter.get ());
337 /* Return a sequence of all fields. Each field is a gdb.Field object. */
340 typy_values (PyObject *self, PyObject *args)
342 return typy_fields_items (self, iter_values);
345 /* Return a sequence of all fields. Each field is a gdb.Field object.
346 This method is similar to typy_values, except where the supplied
347 gdb.Type is an array, in which case it returns a list of one entry
348 which is a gdb.Field object for a range (the array bounds). */
351 typy_fields (PyObject *self, PyObject *args)
353 struct type *type = ((type_object *) self)->type;
355 if (type->code () != TYPE_CODE_ARRAY)
356 return typy_fields_items (self, iter_values);
358 /* Array type. Handle this as a special case because the common
359 machinery wants struct or union or enum types. Build a list of
360 one entry which is the range for the array. */
361 gdbpy_ref<> r = convert_field (type, 0);
365 return Py_BuildValue ("[O]", r.get ());
368 /* Return a sequence of all field names. Each field is a gdb.Field object. */
371 typy_field_names (PyObject *self, PyObject *args)
373 return typy_fields_items (self, iter_keys);
376 /* Return a sequence of all (name, fields) pairs. Each field is a
380 typy_items (PyObject *self, PyObject *args)
382 return typy_fields_items (self, iter_items);
385 /* Return the type's name, or None. */
388 typy_get_name (PyObject *self, void *closure)
390 struct type *type = ((type_object *) self)->type;
392 if (type->name () == NULL)
394 /* Ada type names are encoded, but it is better for users to see the
396 if (ADA_TYPE_P (type))
398 std::string name = ada_decode (type->name (), false);
400 return PyUnicode_FromString (name.c_str ());
402 return PyUnicode_FromString (type->name ());
405 /* Return the type's tag, or None. */
407 typy_get_tag (PyObject *self, void *closure)
409 struct type *type = ((type_object *) self)->type;
410 const char *tagname = nullptr;
412 if (type->code () == TYPE_CODE_STRUCT
413 || type->code () == TYPE_CODE_UNION
414 || type->code () == TYPE_CODE_ENUM)
415 tagname = type->name ();
417 if (tagname == nullptr)
419 return PyUnicode_FromString (tagname);
422 /* Return the type's objfile, or None. */
424 typy_get_objfile (PyObject *self, void *closure)
426 struct type *type = ((type_object *) self)->type;
427 struct objfile *objfile = type->objfile_owner ();
429 if (objfile == nullptr)
431 return objfile_to_objfile_object (objfile).release ();
434 /* Return true if this is a scalar type, otherwise, returns false. */
437 typy_is_scalar (PyObject *self, void *closure)
439 struct type *type = ((type_object *) self)->type;
441 if (is_scalar_type (type))
447 /* Return true if this type is signed. Raises a ValueError if this type
448 is not a scalar type. */
451 typy_is_signed (PyObject *self, void *closure)
453 struct type *type = ((type_object *) self)->type;
455 if (!is_scalar_type (type))
457 PyErr_SetString (PyExc_ValueError,
458 _("Type must be a scalar type"));
462 if (type->is_unsigned ())
468 /* Return the type, stripped of typedefs. */
470 typy_strip_typedefs (PyObject *self, PyObject *args)
472 struct type *type = ((type_object *) self)->type;
476 type = check_typedef (type);
478 catch (const gdb_exception &except)
480 GDB_PY_HANDLE_EXCEPTION (except);
483 return type_to_type_object (type);
486 /* Strip typedefs and pointers/reference from a type. Then check that
487 it is a struct, union, or enum type. If not, raise TypeError. */
490 typy_get_composite (struct type *type)
497 type = check_typedef (type);
499 catch (const gdb_exception &except)
501 GDB_PY_HANDLE_EXCEPTION (except);
504 if (!type->is_pointer_or_reference ())
506 type = type->target_type ();
509 /* If this is not a struct, union, or enum type, raise TypeError
511 if (type->code () != TYPE_CODE_STRUCT
512 && type->code () != TYPE_CODE_UNION
513 && type->code () != TYPE_CODE_ENUM
514 && type->code () != TYPE_CODE_METHOD
515 && type->code () != TYPE_CODE_FUNC)
517 PyErr_SetString (PyExc_TypeError,
518 "Type is not a structure, union, enum, or function type.");
525 /* Helper for typy_array and typy_vector. */
528 typy_array_1 (PyObject *self, PyObject *args, int is_vector)
531 PyObject *n2_obj = NULL;
532 struct type *array = NULL;
533 struct type *type = ((type_object *) self)->type;
535 if (! PyArg_ParseTuple (args, "l|O", &n1, &n2_obj))
540 if (!PyLong_Check (n2_obj))
542 PyErr_SetString (PyExc_RuntimeError,
543 _("Array bound must be an integer"));
547 if (! gdb_py_int_as_long (n2_obj, &n2))
556 if (n2 < n1 - 1) /* Note: An empty array has n2 == n1 - 1. */
558 PyErr_SetString (PyExc_ValueError,
559 _("Array length must not be negative"));
565 array = lookup_array_range_type (type, n1, n2);
567 make_vector_type (array);
569 catch (const gdb_exception &except)
571 GDB_PY_HANDLE_EXCEPTION (except);
574 return type_to_type_object (array);
577 /* Return an array type. */
580 typy_array (PyObject *self, PyObject *args)
582 return typy_array_1 (self, args, 0);
585 /* Return a vector type. */
588 typy_vector (PyObject *self, PyObject *args)
590 return typy_array_1 (self, args, 1);
593 /* Return a Type object which represents a pointer to SELF. */
595 typy_pointer (PyObject *self, PyObject *args)
597 struct type *type = ((type_object *) self)->type;
601 type = lookup_pointer_type (type);
603 catch (const gdb_exception &except)
605 GDB_PY_HANDLE_EXCEPTION (except);
608 return type_to_type_object (type);
611 /* Return the range of a type represented by SELF. The return type is
612 a tuple. The first element of the tuple contains the low bound,
613 while the second element of the tuple contains the high bound. */
615 typy_range (PyObject *self, PyObject *args)
617 struct type *type = ((type_object *) self)->type;
618 /* Initialize these to appease GCC warnings. */
619 LONGEST low = 0, high = 0;
621 if (type->code () != TYPE_CODE_ARRAY
622 && type->code () != TYPE_CODE_STRING
623 && type->code () != TYPE_CODE_RANGE)
625 PyErr_SetString (PyExc_RuntimeError,
626 _("This type does not have a range."));
630 switch (type->code ())
632 case TYPE_CODE_ARRAY:
633 case TYPE_CODE_STRING:
634 case TYPE_CODE_RANGE:
635 if (type->bounds ()->low.kind () == PROP_CONST)
636 low = type->bounds ()->low.const_val ();
640 if (type->bounds ()->high.kind () == PROP_CONST)
641 high = type->bounds ()->high.const_val ();
647 gdbpy_ref<> low_bound = gdb_py_object_from_longest (low);
648 if (low_bound == NULL)
651 gdbpy_ref<> high_bound = gdb_py_object_from_longest (high);
652 if (high_bound == NULL)
655 gdbpy_ref<> result (PyTuple_New (2));
659 if (PyTuple_SetItem (result.get (), 0, low_bound.release ()) != 0
660 || PyTuple_SetItem (result.get (), 1, high_bound.release ()) != 0)
662 return result.release ();
665 /* Return a Type object which represents a reference to SELF. */
667 typy_reference (PyObject *self, PyObject *args)
669 struct type *type = ((type_object *) self)->type;
673 type = lookup_lvalue_reference_type (type);
675 catch (const gdb_exception &except)
677 GDB_PY_HANDLE_EXCEPTION (except);
680 return type_to_type_object (type);
683 /* Return a Type object which represents the target type of SELF. */
685 typy_target (PyObject *self, PyObject *args)
687 struct type *type = ((type_object *) self)->type;
689 if (!type->target_type ())
691 PyErr_SetString (PyExc_RuntimeError,
692 _("Type does not have a target."));
696 return type_to_type_object (type->target_type ());
699 /* Return a const-qualified type variant. */
701 typy_const (PyObject *self, PyObject *args)
703 struct type *type = ((type_object *) self)->type;
707 type = make_cv_type (1, 0, type, NULL);
709 catch (const gdb_exception &except)
711 GDB_PY_HANDLE_EXCEPTION (except);
714 return type_to_type_object (type);
717 /* Return a volatile-qualified type variant. */
719 typy_volatile (PyObject *self, PyObject *args)
721 struct type *type = ((type_object *) self)->type;
725 type = make_cv_type (0, 1, type, NULL);
727 catch (const gdb_exception &except)
729 GDB_PY_HANDLE_EXCEPTION (except);
732 return type_to_type_object (type);
735 /* Return an unqualified type variant. */
737 typy_unqualified (PyObject *self, PyObject *args)
739 struct type *type = ((type_object *) self)->type;
743 type = make_cv_type (0, 0, type, NULL);
745 catch (const gdb_exception &except)
747 GDB_PY_HANDLE_EXCEPTION (except);
750 return type_to_type_object (type);
753 /* Return the size of the type represented by SELF, in bytes. */
755 typy_get_sizeof (PyObject *self, void *closure)
757 struct type *type = ((type_object *) self)->type;
759 bool size_varies = false;
762 check_typedef (type);
764 size_varies = TYPE_HAS_DYNAMIC_LENGTH (type);
766 catch (const gdb_exception &except)
770 /* Ignore exceptions. */
774 return gdb_py_object_from_longest (type->length ()).release ();
777 /* Return the alignment of the type represented by SELF, in bytes. */
779 typy_get_alignof (PyObject *self, void *closure)
781 struct type *type = ((type_object *) self)->type;
786 align = type_align (type);
788 catch (const gdb_exception &except)
793 /* Ignore exceptions. */
795 return gdb_py_object_from_ulongest (align).release ();
798 /* Return whether or not the type is dynamic. */
800 typy_get_dynamic (PyObject *self, void *closure)
802 struct type *type = ((type_object *) self)->type;
807 result = is_dynamic_type (type);
809 catch (const gdb_exception &except)
811 /* Ignore exceptions. */
820 typy_lookup_typename (const char *type_name, const struct block *block)
822 struct type *type = NULL;
826 if (startswith (type_name, "struct "))
827 type = lookup_struct (type_name + 7, NULL);
828 else if (startswith (type_name, "union "))
829 type = lookup_union (type_name + 6, NULL);
830 else if (startswith (type_name, "enum "))
831 type = lookup_enum (type_name + 5, NULL);
833 type = lookup_typename (current_language,
834 type_name, block, 0);
836 catch (const gdb_exception &except)
838 GDB_PY_HANDLE_EXCEPTION (except);
845 typy_lookup_type (struct demangle_component *demangled,
846 const struct block *block)
848 struct type *type, *rtype = NULL;
849 enum demangle_component_type demangled_type;
851 /* Save the type: typy_lookup_type() may (indirectly) overwrite
852 memory pointed by demangled. */
853 demangled_type = demangled->type;
855 if (demangled_type == DEMANGLE_COMPONENT_POINTER
856 || demangled_type == DEMANGLE_COMPONENT_REFERENCE
857 || demangled_type == DEMANGLE_COMPONENT_RVALUE_REFERENCE
858 || demangled_type == DEMANGLE_COMPONENT_CONST
859 || demangled_type == DEMANGLE_COMPONENT_VOLATILE)
861 type = typy_lookup_type (demangled->u.s_binary.left, block);
867 /* If the demangled_type matches with one of the types
868 below, run the corresponding function and save the type
869 to return later. We cannot just return here as we are in
870 an exception handler. */
871 switch (demangled_type)
873 case DEMANGLE_COMPONENT_REFERENCE:
874 rtype = lookup_lvalue_reference_type (type);
876 case DEMANGLE_COMPONENT_RVALUE_REFERENCE:
877 rtype = lookup_rvalue_reference_type (type);
879 case DEMANGLE_COMPONENT_POINTER:
880 rtype = lookup_pointer_type (type);
882 case DEMANGLE_COMPONENT_CONST:
883 rtype = make_cv_type (1, 0, type, NULL);
885 case DEMANGLE_COMPONENT_VOLATILE:
886 rtype = make_cv_type (0, 1, type, NULL);
890 catch (const gdb_exception &except)
892 GDB_PY_HANDLE_EXCEPTION (except);
896 /* If we have a type from the switch statement above, just return
901 /* We don't have a type, so lookup the type. */
902 gdb::unique_xmalloc_ptr<char> type_name = cp_comp_to_string (demangled, 10);
903 return typy_lookup_typename (type_name.get (), block);
906 /* This is a helper function for typy_template_argument that is used
907 when the type does not have template symbols attached. It works by
908 parsing the type name. This happens with compilers, like older
909 versions of GCC, that do not emit DW_TAG_template_*. */
912 typy_legacy_template_argument (struct type *type, const struct block *block,
916 struct demangle_component *demangled;
917 std::unique_ptr<demangle_parse_info> info;
919 struct type *argtype;
921 if (type->name () == NULL)
923 PyErr_SetString (PyExc_RuntimeError, _("Null type name."));
929 /* Note -- this is not thread-safe. */
930 info = cp_demangled_name_to_comp (type->name (), &err);
932 catch (const gdb_exception &except)
934 GDB_PY_HANDLE_EXCEPTION (except);
939 PyErr_SetString (PyExc_RuntimeError, err.c_str ());
942 demangled = info->tree;
944 /* Strip off component names. */
945 while (demangled->type == DEMANGLE_COMPONENT_QUAL_NAME
946 || demangled->type == DEMANGLE_COMPONENT_LOCAL_NAME)
947 demangled = demangled->u.s_binary.right;
949 if (demangled->type != DEMANGLE_COMPONENT_TEMPLATE)
951 PyErr_SetString (PyExc_RuntimeError, _("Type is not a template."));
955 /* Skip from the template to the arguments. */
956 demangled = demangled->u.s_binary.right;
958 for (i = 0; demangled && i < argno; ++i)
959 demangled = demangled->u.s_binary.right;
963 PyErr_Format (PyExc_RuntimeError, _("No argument %d in template."),
968 argtype = typy_lookup_type (demangled->u.s_binary.left, block);
972 return type_to_type_object (argtype);
976 typy_template_argument (PyObject *self, PyObject *args)
979 struct type *type = ((type_object *) self)->type;
980 const struct block *block = NULL;
981 PyObject *block_obj = NULL;
983 struct value *val = NULL;
985 if (! PyArg_ParseTuple (args, "i|O", &argno, &block_obj))
990 PyErr_SetString (PyExc_RuntimeError,
991 _("Template argument number must be non-negative"));
997 block = block_object_to_block (block_obj);
1000 PyErr_SetString (PyExc_RuntimeError,
1001 _("Second argument must be block."));
1008 type = check_typedef (type);
1009 if (TYPE_IS_REFERENCE (type))
1010 type = check_typedef (type->target_type ());
1012 catch (const gdb_exception &except)
1014 GDB_PY_HANDLE_EXCEPTION (except);
1017 /* We might not have DW_TAG_template_*, so try to parse the type's
1018 name. This is inefficient if we do not have a template type --
1019 but that is going to wind up as an error anyhow. */
1020 if (! TYPE_N_TEMPLATE_ARGUMENTS (type))
1021 return typy_legacy_template_argument (type, block, argno);
1023 if (argno >= TYPE_N_TEMPLATE_ARGUMENTS (type))
1025 PyErr_Format (PyExc_RuntimeError, _("No argument %d in template."),
1030 sym = TYPE_TEMPLATE_ARGUMENT (type, argno);
1031 if (sym->aclass () == LOC_TYPEDEF)
1032 return type_to_type_object (sym->type ());
1033 else if (sym->aclass () == LOC_OPTIMIZED_OUT)
1035 PyErr_Format (PyExc_RuntimeError,
1036 _("Template argument is optimized out"));
1042 val = value_of_variable (sym, block);
1044 catch (const gdb_exception &except)
1046 GDB_PY_HANDLE_EXCEPTION (except);
1049 return value_to_value_object (val);
1053 typy_str (PyObject *self)
1055 string_file thetype;
1059 current_language->print_type (type_object_to_type (self), "",
1061 &type_print_raw_options);
1063 catch (const gdb_exception &except)
1065 GDB_PY_HANDLE_EXCEPTION (except);
1068 return PyUnicode_Decode (thetype.c_str (), thetype.size (),
1069 host_charset (), NULL);
1072 /* Implement the richcompare method. */
1075 typy_richcompare (PyObject *self, PyObject *other, int op)
1077 bool result = false;
1078 struct type *type1 = type_object_to_type (self);
1079 struct type *type2 = type_object_to_type (other);
1081 /* We can only compare ourselves to another Type object, and only
1082 for equality or inequality. */
1083 if (type2 == NULL || (op != Py_EQ && op != Py_NE))
1085 Py_INCREF (Py_NotImplemented);
1086 return Py_NotImplemented;
1095 result = types_deeply_equal (type1, type2);
1097 catch (const gdb_exception &except)
1099 /* If there is a GDB exception, a comparison is not capable
1100 (or trusted), so exit. */
1101 GDB_PY_HANDLE_EXCEPTION (except);
1105 if (op == (result ? Py_EQ : Py_NE))
1112 /* Deleter that saves types when an objfile is being destroyed. */
1115 void operator() (type_object *obj)
1117 if (!gdb_python_initialized)
1120 /* This prevents another thread from freeing the objects we're
1122 gdbpy_enter enter_py;
1124 htab_up copied_types = create_copied_types_hash ();
1128 type_object *next = obj->next;
1130 htab_empty (copied_types.get ());
1132 obj->type = copy_type_recursive (obj->type, copied_types.get ());
1142 static const registry<objfile>::key<type_object, typy_deleter>
1143 typy_objfile_data_key;
1146 set_type (type_object *obj, struct type *type)
1150 if (type != nullptr && type->objfile_owner () != nullptr)
1152 struct objfile *objfile = type->objfile_owner ();
1154 obj->next = typy_objfile_data_key.get (objfile);
1156 obj->next->prev = obj;
1157 typy_objfile_data_key.set (objfile, obj);
1164 typy_dealloc (PyObject *obj)
1166 type_object *type = (type_object *) obj;
1169 type->prev->next = type->next;
1170 else if (type->type != nullptr && type->type->objfile_owner () != nullptr)
1172 /* Must reset head of list. */
1173 struct objfile *objfile = type->type->objfile_owner ();
1176 typy_objfile_data_key.set (objfile, type->next);
1179 type->next->prev = type->prev;
1181 Py_TYPE (type)->tp_free (type);
1184 /* Return number of fields ("length" of the field dictionary). */
1187 typy_length (PyObject *self)
1189 struct type *type = ((type_object *) self)->type;
1191 type = typy_get_composite (type);
1195 return type->num_fields ();
1198 /* Implements boolean evaluation of gdb.Type. Handle this like other
1199 Python objects that don't have a meaningful truth value -- all
1203 typy_nonzero (PyObject *self)
1208 /* Return optimized out value of this type. */
1211 typy_optimized_out (PyObject *self, PyObject *args)
1213 struct type *type = ((type_object *) self)->type;
1215 return value_to_value_object (allocate_optimized_out_value (type));
1218 /* Return a gdb.Field object for the field named by the argument. */
1221 typy_getitem (PyObject *self, PyObject *key)
1223 struct type *type = ((type_object *) self)->type;
1226 gdb::unique_xmalloc_ptr<char> field = python_string_to_host_string (key);
1230 /* We want just fields of this type, not of base types, so instead of
1231 using lookup_struct_elt_type, portions of that function are
1234 type = typy_get_composite (type);
1238 for (i = 0; i < type->num_fields (); i++)
1240 const char *t_field_name = type->field (i).name ();
1242 if (t_field_name && (strcmp_iw (t_field_name, field.get ()) == 0))
1243 return convert_field (type, i).release ();
1245 PyErr_SetObject (PyExc_KeyError, key);
1249 /* Implement the "get" method on the type object. This is the
1250 same as getitem if the key is present, but returns the supplied
1251 default value or None if the key is not found. */
1254 typy_get (PyObject *self, PyObject *args)
1256 PyObject *key, *defval = Py_None, *result;
1258 if (!PyArg_UnpackTuple (args, "get", 1, 2, &key, &defval))
1261 result = typy_getitem (self, key);
1265 /* typy_getitem returned error status. If the exception is
1266 KeyError, clear the exception status and return the defval
1267 instead. Otherwise return the exception unchanged. */
1268 if (!PyErr_ExceptionMatches (PyExc_KeyError))
1276 /* Implement the "has_key" method on the type object. */
1279 typy_has_key (PyObject *self, PyObject *args)
1281 struct type *type = ((type_object *) self)->type;
1285 if (!PyArg_ParseTuple (args, "s", &field))
1288 /* We want just fields of this type, not of base types, so instead of
1289 using lookup_struct_elt_type, portions of that function are
1292 type = typy_get_composite (type);
1296 for (i = 0; i < type->num_fields (); i++)
1298 const char *t_field_name = type->field (i).name ();
1300 if (t_field_name && (strcmp_iw (t_field_name, field) == 0))
1306 /* Make an iterator object to iterate over keys, values, or items. */
1309 typy_make_iter (PyObject *self, enum gdbpy_iter_kind kind)
1311 typy_iterator_object *typy_iter_obj;
1313 /* Check that "self" is a structure or union type. */
1314 if (typy_get_composite (((type_object *) self)->type) == NULL)
1317 typy_iter_obj = PyObject_New (typy_iterator_object,
1318 &type_iterator_object_type);
1319 if (typy_iter_obj == NULL)
1322 typy_iter_obj->field = 0;
1323 typy_iter_obj->kind = kind;
1325 typy_iter_obj->source = (type_object *) self;
1327 return (PyObject *) typy_iter_obj;
1330 /* iteritems() method. */
1333 typy_iteritems (PyObject *self, PyObject *args)
1335 return typy_make_iter (self, iter_items);
1338 /* iterkeys() method. */
1341 typy_iterkeys (PyObject *self, PyObject *args)
1343 return typy_make_iter (self, iter_keys);
1346 /* Iterating over the class, same as iterkeys except for the function
1350 typy_iter (PyObject *self)
1352 return typy_make_iter (self, iter_keys);
1355 /* itervalues() method. */
1358 typy_itervalues (PyObject *self, PyObject *args)
1360 return typy_make_iter (self, iter_values);
1363 /* Return a reference to the type iterator. */
1366 typy_iterator_iter (PyObject *self)
1372 /* Return the next field in the iteration through the list of fields
1376 typy_iterator_iternext (PyObject *self)
1378 typy_iterator_object *iter_obj = (typy_iterator_object *) self;
1379 struct type *type = iter_obj->source->type;
1381 if (iter_obj->field < type->num_fields ())
1383 gdbpy_ref<> result = make_fielditem (type, iter_obj->field,
1387 return result.release ();
1394 typy_iterator_dealloc (PyObject *obj)
1396 typy_iterator_object *iter_obj = (typy_iterator_object *) obj;
1398 Py_DECREF (iter_obj->source);
1399 Py_TYPE (obj)->tp_free (obj);
1402 /* Create a new Type referring to TYPE. */
1404 type_to_type_object (struct type *type)
1406 type_object *type_obj;
1410 /* Try not to let stub types leak out to Python. */
1411 if (type->is_stub ())
1412 type = check_typedef (type);
1416 /* Just ignore failures in check_typedef. */
1419 type_obj = PyObject_New (type_object, &type_object_type);
1421 set_type (type_obj, type);
1423 return (PyObject *) type_obj;
1427 type_object_to_type (PyObject *obj)
1429 if (! PyObject_TypeCheck (obj, &type_object_type))
1431 return ((type_object *) obj)->type;
1436 /* Implementation of gdb.lookup_type. */
1438 gdbpy_lookup_type (PyObject *self, PyObject *args, PyObject *kw)
1440 static const char *keywords[] = { "name", "block", NULL };
1441 const char *type_name = NULL;
1442 struct type *type = NULL;
1443 PyObject *block_obj = NULL;
1444 const struct block *block = NULL;
1446 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O", keywords,
1447 &type_name, &block_obj))
1452 block = block_object_to_block (block_obj);
1455 PyErr_SetString (PyExc_RuntimeError,
1456 _("'block' argument must be a Block."));
1461 type = typy_lookup_typename (type_name, block);
1465 return type_to_type_object (type);
1469 gdbpy_initialize_types (void)
1471 if (PyType_Ready (&type_object_type) < 0)
1473 if (PyType_Ready (&field_object_type) < 0)
1475 if (PyType_Ready (&type_iterator_object_type) < 0)
1478 for (const auto &item : pyty_codes)
1480 if (PyModule_AddIntConstant (gdb_module, item.name, item.code) < 0)
1484 if (gdb_pymodule_addobject (gdb_module, "Type",
1485 (PyObject *) &type_object_type) < 0)
1488 if (gdb_pymodule_addobject (gdb_module, "TypeIterator",
1489 (PyObject *) &type_iterator_object_type) < 0)
1492 return gdb_pymodule_addobject (gdb_module, "Field",
1493 (PyObject *) &field_object_type);
1498 static gdb_PyGetSetDef type_object_getset[] =
1500 { "alignof", typy_get_alignof, NULL,
1501 "The alignment of this type, in bytes.", NULL },
1502 { "code", typy_get_code, NULL,
1503 "The code for this type.", NULL },
1504 { "dynamic", typy_get_dynamic, NULL,
1505 "Whether this type is dynamic.", NULL },
1506 { "name", typy_get_name, NULL,
1507 "The name for this type, or None.", NULL },
1508 { "sizeof", typy_get_sizeof, NULL,
1509 "The size of this type, in bytes.", NULL },
1510 { "tag", typy_get_tag, NULL,
1511 "The tag name for this type, or None.", NULL },
1512 { "objfile", typy_get_objfile, NULL,
1513 "The objfile this type was defined in, or None.", NULL },
1514 { "is_scalar", typy_is_scalar, nullptr,
1515 "Is this a scalar type?", nullptr },
1516 { "is_signed", typy_is_signed, nullptr,
1517 "Is this an signed type?", nullptr },
1521 static PyMethodDef type_object_methods[] =
1523 { "array", typy_array, METH_VARARGS,
1524 "array ([LOW_BOUND,] HIGH_BOUND) -> Type\n\
1525 Return a type which represents an array of objects of this type.\n\
1526 The bounds of the array are [LOW_BOUND, HIGH_BOUND] inclusive.\n\
1527 If LOW_BOUND is omitted, a value of zero is used." },
1528 { "vector", typy_vector, METH_VARARGS,
1529 "vector ([LOW_BOUND,] HIGH_BOUND) -> Type\n\
1530 Return a type which represents a vector of objects of this type.\n\
1531 The bounds of the array are [LOW_BOUND, HIGH_BOUND] inclusive.\n\
1532 If LOW_BOUND is omitted, a value of zero is used.\n\
1533 Vectors differ from arrays in that if the current language has C-style\n\
1534 arrays, vectors don't decay to a pointer to the first element.\n\
1535 They are first class values." },
1536 { "__contains__", typy_has_key, METH_VARARGS,
1537 "T.__contains__(k) -> True if T has a field named k, else False" },
1538 { "const", typy_const, METH_NOARGS,
1539 "const () -> Type\n\
1540 Return a const variant of this type." },
1541 { "optimized_out", typy_optimized_out, METH_NOARGS,
1542 "optimized_out() -> Value\n\
1543 Return optimized out value of this type." },
1544 { "fields", typy_fields, METH_NOARGS,
1545 "fields () -> list\n\
1546 Return a list holding all the fields of this type.\n\
1547 Each field is a gdb.Field object." },
1548 { "get", typy_get, METH_VARARGS,
1549 "T.get(k[,default]) -> returns field named k in T, if it exists;\n\
1550 otherwise returns default, if supplied, or None if not." },
1551 { "has_key", typy_has_key, METH_VARARGS,
1552 "T.has_key(k) -> True if T has a field named k, else False" },
1553 { "items", typy_items, METH_NOARGS,
1554 "items () -> list\n\
1555 Return a list of (name, field) pairs of this type.\n\
1556 Each field is a gdb.Field object." },
1557 { "iteritems", typy_iteritems, METH_NOARGS,
1558 "iteritems () -> an iterator over the (name, field)\n\
1559 pairs of this type. Each field is a gdb.Field object." },
1560 { "iterkeys", typy_iterkeys, METH_NOARGS,
1561 "iterkeys () -> an iterator over the field names of this type." },
1562 { "itervalues", typy_itervalues, METH_NOARGS,
1563 "itervalues () -> an iterator over the fields of this type.\n\
1564 Each field is a gdb.Field object." },
1565 { "keys", typy_field_names, METH_NOARGS,
1567 Return a list holding all the fields names of this type." },
1568 { "pointer", typy_pointer, METH_NOARGS,
1569 "pointer () -> Type\n\
1570 Return a type of pointer to this type." },
1571 { "range", typy_range, METH_NOARGS,
1572 "range () -> tuple\n\
1573 Return a tuple containing the lower and upper range for this type."},
1574 { "reference", typy_reference, METH_NOARGS,
1575 "reference () -> Type\n\
1576 Return a type of reference to this type." },
1577 { "strip_typedefs", typy_strip_typedefs, METH_NOARGS,
1578 "strip_typedefs () -> Type\n\
1579 Return a type formed by stripping this type of all typedefs."},
1580 { "target", typy_target, METH_NOARGS,
1581 "target () -> Type\n\
1582 Return the target type of this type." },
1583 { "template_argument", typy_template_argument, METH_VARARGS,
1584 "template_argument (arg, [block]) -> Type\n\
1585 Return the type of a template argument." },
1586 { "unqualified", typy_unqualified, METH_NOARGS,
1587 "unqualified () -> Type\n\
1588 Return a variant of this type without const or volatile attributes." },
1589 { "values", typy_values, METH_NOARGS,
1590 "values () -> list\n\
1591 Return a list holding all the fields of this type.\n\
1592 Each field is a gdb.Field object." },
1593 { "volatile", typy_volatile, METH_NOARGS,
1594 "volatile () -> Type\n\
1595 Return a volatile variant of this type" },
1599 static PyNumberMethods type_object_as_number = {
1601 NULL, /* nb_subtract */
1602 NULL, /* nb_multiply */
1603 NULL, /* nb_remainder */
1604 NULL, /* nb_divmod */
1605 NULL, /* nb_power */
1606 NULL, /* nb_negative */
1607 NULL, /* nb_positive */
1608 NULL, /* nb_absolute */
1609 typy_nonzero, /* nb_nonzero */
1610 NULL, /* nb_invert */
1611 NULL, /* nb_lshift */
1612 NULL, /* nb_rshift */
1617 NULL, /* reserved */
1618 NULL, /* nb_float */
1621 static PyMappingMethods typy_mapping = {
1624 NULL /* no "set" method */
1627 PyTypeObject type_object_type =
1629 PyVarObject_HEAD_INIT (NULL, 0)
1630 "gdb.Type", /*tp_name*/
1631 sizeof (type_object), /*tp_basicsize*/
1633 typy_dealloc, /*tp_dealloc*/
1639 &type_object_as_number, /*tp_as_number*/
1640 0, /*tp_as_sequence*/
1641 &typy_mapping, /*tp_as_mapping*/
1644 typy_str, /*tp_str*/
1648 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1649 "GDB type object", /* tp_doc */
1650 0, /* tp_traverse */
1652 typy_richcompare, /* tp_richcompare */
1653 0, /* tp_weaklistoffset */
1654 typy_iter, /* tp_iter */
1655 0, /* tp_iternext */
1656 type_object_methods, /* tp_methods */
1658 type_object_getset, /* tp_getset */
1661 0, /* tp_descr_get */
1662 0, /* tp_descr_set */
1663 0, /* tp_dictoffset */
1669 static gdb_PyGetSetDef field_object_getset[] =
1671 { "__dict__", gdb_py_generic_dict, NULL,
1672 "The __dict__ for this field.", &field_object_type },
1676 PyTypeObject field_object_type =
1678 PyVarObject_HEAD_INIT (NULL, 0)
1679 "gdb.Field", /*tp_name*/
1680 sizeof (field_object), /*tp_basicsize*/
1682 field_dealloc, /*tp_dealloc*/
1689 0, /*tp_as_sequence*/
1690 0, /*tp_as_mapping*/
1697 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1698 "GDB field object", /* tp_doc */
1699 0, /* tp_traverse */
1701 0, /* tp_richcompare */
1702 0, /* tp_weaklistoffset */
1704 0, /* tp_iternext */
1707 field_object_getset, /* tp_getset */
1710 0, /* tp_descr_get */
1711 0, /* tp_descr_set */
1712 offsetof (field_object, dict), /* tp_dictoffset */
1718 PyTypeObject type_iterator_object_type = {
1719 PyVarObject_HEAD_INIT (NULL, 0)
1720 "gdb.TypeIterator", /*tp_name*/
1721 sizeof (typy_iterator_object), /*tp_basicsize*/
1723 typy_iterator_dealloc, /*tp_dealloc*/
1730 0, /*tp_as_sequence*/
1731 0, /*tp_as_mapping*/
1738 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1739 "GDB type iterator object", /*tp_doc */
1742 0, /*tp_richcompare */
1743 0, /*tp_weaklistoffset */
1744 typy_iterator_iter, /*tp_iter */
1745 typy_iterator_iternext, /*tp_iternext */