1 /* Python interface to types.
3 Copyright (C) 2008-2024 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/>. */
21 #include "python-internal.h"
24 #include "cp-support.h"
28 #include "typeprint.h"
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 type_object
*prev
;
40 struct type_object
*next
;
43 extern PyTypeObject type_object_type
44 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("type_object");
51 /* Dictionary holding our attributes. */
55 extern PyTypeObject field_object_type
56 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("field_object");
58 /* A type iterator object. */
59 struct typy_iterator_object
{
61 /* The current field index. */
64 enum gdbpy_iter_kind kind
;
65 /* Pointer back to the original source type object. */
69 extern PyTypeObject type_iterator_object_type
70 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("typy_iterator_object");
72 /* This is used to initialize various gdb.TYPE_ constants. */
81 /* Forward declarations. */
82 static PyObject
*typy_make_iter (PyObject
*self
, enum gdbpy_iter_kind kind
);
84 static struct pyty_code pyty_codes
[] =
86 /* This is kept for backward compatibility. */
87 { -1, "TYPE_CODE_BITSTRING" },
89 #define OP(X) { X, #X },
90 #include "type-codes.def"
97 field_dealloc (PyObject
*obj
)
99 field_object
*f
= (field_object
*) obj
;
101 Py_XDECREF (f
->dict
);
102 Py_TYPE (obj
)->tp_free (obj
);
108 gdbpy_ref
<field_object
> result (PyObject_New (field_object
,
109 &field_object_type
));
113 result
->dict
= PyDict_New ();
117 return (PyObject
*) result
.release ();
122 /* Return true if OBJ is of type gdb.Field, false otherwise. */
125 gdbpy_is_field (PyObject
*obj
)
127 return PyObject_TypeCheck (obj
, &field_object_type
);
130 /* Return the code for this type. */
132 typy_get_code (PyObject
*self
, void *closure
)
134 struct type
*type
= ((type_object
*) self
)->type
;
136 return gdb_py_object_from_longest (type
->code ()).release ();
139 /* Helper function for typy_fields which converts a single field to a
140 gdb.Field object. Returns NULL on error. */
143 convert_field (struct type
*type
, int field
)
145 gdbpy_ref
<> result (field_new ());
150 gdbpy_ref
<> arg (type_to_type_object (type
));
153 if (PyObject_SetAttrString (result
.get (), "parent_type", arg
.get ()) < 0)
156 if (!type
->field (field
).is_static ())
158 const char *attrstring
;
160 if (type
->code () == TYPE_CODE_ENUM
)
162 arg
= gdb_py_object_from_longest (type
->field (field
).loc_enumval ());
163 attrstring
= "enumval";
167 if (type
->field (field
).loc_kind () == FIELD_LOC_KIND_DWARF_BLOCK
)
168 arg
= gdbpy_ref
<>::new_reference (Py_None
);
170 arg
= gdb_py_object_from_longest (type
->field (field
).loc_bitpos ());
171 attrstring
= "bitpos";
177 if (PyObject_SetAttrString (result
.get (), attrstring
, arg
.get ()) < 0)
182 if (type
->field (field
).name ())
184 const char *field_name
= type
->field (field
).name ();
186 if (field_name
[0] != '\0')
188 arg
.reset (PyUnicode_FromString (type
->field (field
).name ()));
194 arg
= gdbpy_ref
<>::new_reference (Py_None
);
196 if (PyObject_SetAttrString (result
.get (), "name", arg
.get ()) < 0)
199 arg
.reset (PyBool_FromLong (type
->field (field
).is_artificial ()));
200 if (PyObject_SetAttrString (result
.get (), "artificial", arg
.get ()) < 0)
203 if (type
->code () == TYPE_CODE_STRUCT
)
204 arg
.reset (PyBool_FromLong (field
< TYPE_N_BASECLASSES (type
)));
206 arg
= gdbpy_ref
<>::new_reference (Py_False
);
207 if (PyObject_SetAttrString (result
.get (), "is_base_class", arg
.get ()) < 0)
210 arg
= gdb_py_object_from_longest (type
->field (field
).bitsize ());
213 if (PyObject_SetAttrString (result
.get (), "bitsize", arg
.get ()) < 0)
216 /* A field can have a NULL type in some situations. */
217 if (type
->field (field
).type () == NULL
)
218 arg
= gdbpy_ref
<>::new_reference (Py_None
);
220 arg
.reset (type_to_type_object (type
->field (field
).type ()));
223 if (PyObject_SetAttrString (result
.get (), "type", arg
.get ()) < 0)
229 /* Helper function to return the name of a field, as a gdb.Field object.
230 If the field doesn't have a name, None is returned. */
233 field_name (struct type
*type
, int field
)
237 if (type
->field (field
).name ())
238 result
.reset (PyUnicode_FromString (type
->field (field
).name ()));
240 result
= gdbpy_ref
<>::new_reference (Py_None
);
245 /* Helper function for Type standard mapping methods. Returns a
246 Python object for field i of the type. "kind" specifies what to
247 return: the name of the field, a gdb.Field object corresponding to
248 the field, or a tuple consisting of field name and gdb.Field
252 make_fielditem (struct type
*type
, int i
, enum gdbpy_iter_kind kind
)
258 gdbpy_ref
<> key (field_name (type
, i
));
261 gdbpy_ref
<> value
= convert_field (type
, i
);
264 gdbpy_ref
<> item (PyTuple_New (2));
267 PyTuple_SET_ITEM (item
.get (), 0, key
.release ());
268 PyTuple_SET_ITEM (item
.get (), 1, value
.release ());
272 return field_name (type
, i
);
274 return convert_field (type
, i
);
276 gdb_assert_not_reached ("invalid gdbpy_iter_kind");
279 /* Return a sequence of all field names, fields, or (name, field) pairs.
280 Each field is a gdb.Field object. */
283 typy_fields_items (PyObject
*self
, enum gdbpy_iter_kind kind
)
285 PyObject
*py_type
= self
;
286 struct type
*type
= ((type_object
*) py_type
)->type
;
287 struct type
*checked_type
= type
;
291 checked_type
= check_typedef (checked_type
);
293 catch (const gdb_exception
&except
)
295 return gdbpy_handle_gdb_exception (nullptr, except
);
298 gdbpy_ref
<> type_holder
;
299 if (checked_type
!= type
)
301 type_holder
.reset (type_to_type_object (checked_type
));
302 if (type_holder
== nullptr)
304 py_type
= type_holder
.get ();
306 gdbpy_ref
<> iter (typy_make_iter (py_type
, kind
));
310 return PySequence_List (iter
.get ());
313 /* Return a sequence of all fields. Each field is a gdb.Field object. */
316 typy_values (PyObject
*self
, PyObject
*args
)
318 return typy_fields_items (self
, iter_values
);
321 /* Return a sequence of all fields. Each field is a gdb.Field object.
322 This method is similar to typy_values, except where the supplied
323 gdb.Type is an array, in which case it returns a list of one entry
324 which is a gdb.Field object for a range (the array bounds). */
327 typy_fields (PyObject
*self
, PyObject
*args
)
329 struct type
*type
= ((type_object
*) self
)->type
;
331 if (type
->code () != TYPE_CODE_ARRAY
)
332 return typy_fields_items (self
, iter_values
);
334 /* Array type. Handle this as a special case because the common
335 machinery wants struct or union or enum types. Build a list of
336 one entry which is the range for the array. */
337 gdbpy_ref
<> r
= convert_field (type
, 0);
341 return Py_BuildValue ("[O]", r
.get ());
344 /* Return a sequence of all field names. Each field is a gdb.Field object. */
347 typy_field_names (PyObject
*self
, PyObject
*args
)
349 return typy_fields_items (self
, iter_keys
);
352 /* Return a sequence of all (name, fields) pairs. Each field is a
356 typy_items (PyObject
*self
, PyObject
*args
)
358 return typy_fields_items (self
, iter_items
);
361 /* Return the type's name, or None. */
364 typy_get_name (PyObject
*self
, void *closure
)
366 struct type
*type
= ((type_object
*) self
)->type
;
368 if (type
->name () == NULL
)
370 /* Ada type names are encoded, but it is better for users to see the
372 if (ADA_TYPE_P (type
))
374 std::string name
= ada_decode (type
->name (), false);
376 return PyUnicode_FromString (name
.c_str ());
378 return PyUnicode_FromString (type
->name ());
381 /* Return the type's tag, or None. */
383 typy_get_tag (PyObject
*self
, void *closure
)
385 struct type
*type
= ((type_object
*) self
)->type
;
386 const char *tagname
= nullptr;
388 if (type
->code () == TYPE_CODE_STRUCT
389 || type
->code () == TYPE_CODE_UNION
390 || type
->code () == TYPE_CODE_ENUM
)
391 tagname
= type
->name ();
393 if (tagname
== nullptr)
395 return PyUnicode_FromString (tagname
);
398 /* Return the type's objfile, or None. */
400 typy_get_objfile (PyObject
*self
, void *closure
)
402 struct type
*type
= ((type_object
*) self
)->type
;
403 struct objfile
*objfile
= type
->objfile_owner ();
405 if (objfile
== nullptr)
407 return objfile_to_objfile_object (objfile
).release ();
410 /* Return true if this is a scalar type, otherwise, returns false. */
413 typy_is_scalar (PyObject
*self
, void *closure
)
415 struct type
*type
= ((type_object
*) self
)->type
;
417 if (is_scalar_type (type
))
423 /* Return true if this type is signed. Raises a ValueError if this type
424 is not a scalar type. */
427 typy_is_signed (PyObject
*self
, void *closure
)
429 struct type
*type
= ((type_object
*) self
)->type
;
431 if (!is_scalar_type (type
))
433 PyErr_SetString (PyExc_ValueError
,
434 _("Type must be a scalar type"));
438 if (type
->is_unsigned ())
444 /* Return true if this type is array-like. */
447 typy_is_array_like (PyObject
*self
, void *closure
)
449 struct type
*type
= ((type_object
*) self
)->type
;
454 type
= check_typedef (type
);
455 result
= type
->is_array_like ();
457 catch (const gdb_exception
&except
)
459 return gdbpy_handle_gdb_exception (nullptr, except
);
468 /* Return true if this type is string-like. */
471 typy_is_string_like (PyObject
*self
, void *closure
)
473 struct type
*type
= ((type_object
*) self
)->type
;
478 type
= check_typedef (type
);
479 result
= type
->is_string_like ();
481 catch (const gdb_exception
&except
)
483 return gdbpy_handle_gdb_exception (nullptr, except
);
492 /* Return the type, stripped of typedefs. */
494 typy_strip_typedefs (PyObject
*self
, PyObject
*args
)
496 struct type
*type
= ((type_object
*) self
)->type
;
500 type
= check_typedef (type
);
502 catch (const gdb_exception
&except
)
504 return gdbpy_handle_gdb_exception (nullptr, except
);
507 return type_to_type_object (type
);
510 /* Strip typedefs and pointers/reference from a type. Then check that
511 it is a struct, union, or enum type. If not, raise TypeError. */
514 typy_get_composite (struct type
*type
)
521 type
= check_typedef (type
);
523 catch (const gdb_exception
&except
)
525 return gdbpy_handle_gdb_exception (nullptr, except
);
528 if (!type
->is_pointer_or_reference ())
530 type
= type
->target_type ();
533 /* If this is not a struct, union, or enum type, raise TypeError
535 if (type
->code () != TYPE_CODE_STRUCT
536 && type
->code () != TYPE_CODE_UNION
537 && type
->code () != TYPE_CODE_ENUM
538 && type
->code () != TYPE_CODE_METHOD
539 && type
->code () != TYPE_CODE_FUNC
)
541 PyErr_SetString (PyExc_TypeError
,
542 "Type is not a structure, union, enum, or function type.");
549 /* Helper for typy_array and typy_vector. */
552 typy_array_1 (PyObject
*self
, PyObject
*args
, int is_vector
)
555 PyObject
*n2_obj
= NULL
;
556 struct type
*array
= NULL
;
557 struct type
*type
= ((type_object
*) self
)->type
;
559 if (! PyArg_ParseTuple (args
, "l|O", &n1
, &n2_obj
))
564 if (!PyLong_Check (n2_obj
))
566 PyErr_SetString (PyExc_RuntimeError
,
567 _("Array bound must be an integer"));
571 if (! gdb_py_int_as_long (n2_obj
, &n2
))
580 if (n2
< n1
- 1) /* Note: An empty array has n2 == n1 - 1. */
582 PyErr_SetString (PyExc_ValueError
,
583 _("Array length must not be negative"));
589 array
= lookup_array_range_type (type
, n1
, n2
);
591 make_vector_type (array
);
593 catch (const gdb_exception
&except
)
595 return gdbpy_handle_gdb_exception (nullptr, except
);
598 return type_to_type_object (array
);
601 /* Return an array type. */
604 typy_array (PyObject
*self
, PyObject
*args
)
606 return typy_array_1 (self
, args
, 0);
609 /* Return a vector type. */
612 typy_vector (PyObject
*self
, PyObject
*args
)
614 return typy_array_1 (self
, args
, 1);
617 /* Return a Type object which represents a pointer to SELF. */
619 typy_pointer (PyObject
*self
, PyObject
*args
)
621 struct type
*type
= ((type_object
*) self
)->type
;
625 type
= lookup_pointer_type (type
);
627 catch (const gdb_exception
&except
)
629 return gdbpy_handle_gdb_exception (nullptr, except
);
632 return type_to_type_object (type
);
635 /* Return the range of a type represented by SELF. The return type is
636 a tuple. The first element of the tuple contains the low bound,
637 while the second element of the tuple contains the high bound. */
639 typy_range (PyObject
*self
, PyObject
*args
)
641 struct type
*type
= ((type_object
*) self
)->type
;
642 /* Initialize these to appease GCC warnings. */
643 LONGEST low
= 0, high
= 0;
645 if (type
->code () != TYPE_CODE_ARRAY
646 && type
->code () != TYPE_CODE_STRING
647 && type
->code () != TYPE_CODE_RANGE
)
649 PyErr_SetString (PyExc_RuntimeError
,
650 _("This type does not have a range."));
654 switch (type
->code ())
656 case TYPE_CODE_ARRAY
:
657 case TYPE_CODE_STRING
:
658 case TYPE_CODE_RANGE
:
659 if (type
->bounds ()->low
.is_constant ())
660 low
= type
->bounds ()->low
.const_val ();
664 if (type
->bounds ()->high
.is_constant ())
665 high
= type
->bounds ()->high
.const_val ();
671 gdbpy_ref
<> low_bound
= gdb_py_object_from_longest (low
);
672 if (low_bound
== NULL
)
675 gdbpy_ref
<> high_bound
= gdb_py_object_from_longest (high
);
676 if (high_bound
== NULL
)
679 gdbpy_ref
<> result (PyTuple_New (2));
683 if (PyTuple_SetItem (result
.get (), 0, low_bound
.release ()) != 0
684 || PyTuple_SetItem (result
.get (), 1, high_bound
.release ()) != 0)
686 return result
.release ();
689 /* Return a Type object which represents a reference to SELF. */
691 typy_reference (PyObject
*self
, PyObject
*args
)
693 struct type
*type
= ((type_object
*) self
)->type
;
697 type
= lookup_lvalue_reference_type (type
);
699 catch (const gdb_exception
&except
)
701 return gdbpy_handle_gdb_exception (nullptr, except
);
704 return type_to_type_object (type
);
707 /* Return a Type object which represents the target type of SELF. */
709 typy_target (PyObject
*self
, PyObject
*args
)
711 struct type
*type
= ((type_object
*) self
)->type
;
713 if (!type
->target_type ())
715 PyErr_SetString (PyExc_RuntimeError
,
716 _("Type does not have a target."));
720 return type_to_type_object (type
->target_type ());
723 /* Return a const-qualified type variant. */
725 typy_const (PyObject
*self
, PyObject
*args
)
727 struct type
*type
= ((type_object
*) self
)->type
;
731 type
= make_cv_type (1, 0, type
, NULL
);
733 catch (const gdb_exception
&except
)
735 return gdbpy_handle_gdb_exception (nullptr, except
);
738 return type_to_type_object (type
);
741 /* Return a volatile-qualified type variant. */
743 typy_volatile (PyObject
*self
, PyObject
*args
)
745 struct type
*type
= ((type_object
*) self
)->type
;
749 type
= make_cv_type (0, 1, type
, NULL
);
751 catch (const gdb_exception
&except
)
753 return gdbpy_handle_gdb_exception (nullptr, except
);
756 return type_to_type_object (type
);
759 /* Return an unqualified type variant. */
761 typy_unqualified (PyObject
*self
, PyObject
*args
)
763 struct type
*type
= ((type_object
*) self
)->type
;
767 type
= make_cv_type (0, 0, type
, NULL
);
769 catch (const gdb_exception
&except
)
771 return gdbpy_handle_gdb_exception (nullptr, except
);
774 return type_to_type_object (type
);
777 /* Return the size of the type represented by SELF, in bytes. */
779 typy_get_sizeof (PyObject
*self
, void *closure
)
781 struct type
*type
= ((type_object
*) self
)->type
;
783 bool size_varies
= false;
786 check_typedef (type
);
788 size_varies
= TYPE_HAS_DYNAMIC_LENGTH (type
);
790 catch (const gdb_exception
&except
)
794 /* Ignore exceptions. */
798 return gdb_py_object_from_longest (type
->length ()).release ();
801 /* Return the alignment of the type represented by SELF, in bytes. */
803 typy_get_alignof (PyObject
*self
, void *closure
)
805 struct type
*type
= ((type_object
*) self
)->type
;
810 align
= type_align (type
);
812 catch (const gdb_exception
&except
)
817 /* Ignore exceptions. */
819 return gdb_py_object_from_ulongest (align
).release ();
822 /* Return whether or not the type is dynamic. */
824 typy_get_dynamic (PyObject
*self
, void *closure
)
826 struct type
*type
= ((type_object
*) self
)->type
;
831 result
= is_dynamic_type (type
);
833 catch (const gdb_exception
&except
)
835 /* Ignore exceptions. */
844 typy_lookup_typename (const char *type_name
, const struct block
*block
)
846 struct type
*type
= NULL
;
850 if (startswith (type_name
, "struct "))
851 type
= lookup_struct (type_name
+ 7, NULL
);
852 else if (startswith (type_name
, "union "))
853 type
= lookup_union (type_name
+ 6, NULL
);
854 else if (startswith (type_name
, "enum "))
855 type
= lookup_enum (type_name
+ 5, NULL
);
857 type
= lookup_typename (current_language
,
858 type_name
, block
, 0);
860 catch (const gdb_exception
&except
)
862 return gdbpy_handle_gdb_exception (nullptr, except
);
869 typy_lookup_type (struct demangle_component
*demangled
,
870 const struct block
*block
)
872 struct type
*type
, *rtype
= NULL
;
873 enum demangle_component_type demangled_type
;
875 /* Save the type: typy_lookup_type() may (indirectly) overwrite
876 memory pointed by demangled. */
877 demangled_type
= demangled
->type
;
879 if (demangled_type
== DEMANGLE_COMPONENT_POINTER
880 || demangled_type
== DEMANGLE_COMPONENT_REFERENCE
881 || demangled_type
== DEMANGLE_COMPONENT_RVALUE_REFERENCE
882 || demangled_type
== DEMANGLE_COMPONENT_CONST
883 || demangled_type
== DEMANGLE_COMPONENT_VOLATILE
)
885 type
= typy_lookup_type (demangled
->u
.s_binary
.left
, block
);
891 /* If the demangled_type matches with one of the types
892 below, run the corresponding function and save the type
893 to return later. We cannot just return here as we are in
894 an exception handler. */
895 switch (demangled_type
)
897 case DEMANGLE_COMPONENT_REFERENCE
:
898 rtype
= lookup_lvalue_reference_type (type
);
900 case DEMANGLE_COMPONENT_RVALUE_REFERENCE
:
901 rtype
= lookup_rvalue_reference_type (type
);
903 case DEMANGLE_COMPONENT_POINTER
:
904 rtype
= lookup_pointer_type (type
);
906 case DEMANGLE_COMPONENT_CONST
:
907 rtype
= make_cv_type (1, 0, type
, NULL
);
909 case DEMANGLE_COMPONENT_VOLATILE
:
910 rtype
= make_cv_type (0, 1, type
, NULL
);
914 catch (const gdb_exception
&except
)
916 return gdbpy_handle_gdb_exception (nullptr, except
);
920 /* If we have a type from the switch statement above, just return
925 /* We don't have a type, so lookup the type. */
926 gdb::unique_xmalloc_ptr
<char> type_name
= cp_comp_to_string (demangled
, 10);
927 return typy_lookup_typename (type_name
.get (), block
);
930 /* This is a helper function for typy_template_argument that is used
931 when the type does not have template symbols attached. It works by
932 parsing the type name. This happens with compilers, like older
933 versions of GCC, that do not emit DW_TAG_template_*. */
936 typy_legacy_template_argument (struct type
*type
, const struct block
*block
,
940 struct demangle_component
*demangled
;
941 std::unique_ptr
<demangle_parse_info
> info
;
943 struct type
*argtype
;
945 if (type
->name () == NULL
)
947 PyErr_SetString (PyExc_RuntimeError
, _("Null type name."));
953 /* Note -- this is not thread-safe. */
954 info
= cp_demangled_name_to_comp (type
->name (), &err
);
956 catch (const gdb_exception
&except
)
958 return gdbpy_handle_gdb_exception (nullptr, except
);
963 PyErr_SetString (PyExc_RuntimeError
, err
.c_str ());
966 demangled
= info
->tree
;
968 /* Strip off component names. */
969 while (demangled
->type
== DEMANGLE_COMPONENT_QUAL_NAME
970 || demangled
->type
== DEMANGLE_COMPONENT_LOCAL_NAME
)
971 demangled
= demangled
->u
.s_binary
.right
;
973 if (demangled
->type
!= DEMANGLE_COMPONENT_TEMPLATE
)
975 PyErr_SetString (PyExc_RuntimeError
, _("Type is not a template."));
979 /* Skip from the template to the arguments. */
980 demangled
= demangled
->u
.s_binary
.right
;
982 for (i
= 0; demangled
&& i
< argno
; ++i
)
983 demangled
= demangled
->u
.s_binary
.right
;
987 PyErr_Format (PyExc_RuntimeError
, _("No argument %d in template."),
992 argtype
= typy_lookup_type (demangled
->u
.s_binary
.left
, block
);
996 return type_to_type_object (argtype
);
1000 typy_template_argument (PyObject
*self
, PyObject
*args
)
1003 struct type
*type
= ((type_object
*) self
)->type
;
1004 const struct block
*block
= NULL
;
1005 PyObject
*block_obj
= NULL
;
1008 if (! PyArg_ParseTuple (args
, "i|O", &argno
, &block_obj
))
1013 PyErr_SetString (PyExc_RuntimeError
,
1014 _("Template argument number must be non-negative"));
1020 block
= block_object_to_block (block_obj
);
1023 PyErr_SetString (PyExc_RuntimeError
,
1024 _("Second argument must be block."));
1031 type
= check_typedef (type
);
1032 if (TYPE_IS_REFERENCE (type
))
1033 type
= check_typedef (type
->target_type ());
1035 catch (const gdb_exception
&except
)
1037 return gdbpy_handle_gdb_exception (nullptr, except
);
1040 /* We might not have DW_TAG_template_*, so try to parse the type's
1041 name. This is inefficient if we do not have a template type --
1042 but that is going to wind up as an error anyhow. */
1043 if (! TYPE_N_TEMPLATE_ARGUMENTS (type
))
1044 return typy_legacy_template_argument (type
, block
, argno
);
1046 if (argno
>= TYPE_N_TEMPLATE_ARGUMENTS (type
))
1048 PyErr_Format (PyExc_RuntimeError
, _("No argument %d in template."),
1053 sym
= TYPE_TEMPLATE_ARGUMENT (type
, argno
);
1054 if (sym
->aclass () == LOC_TYPEDEF
)
1055 return type_to_type_object (sym
->type ());
1056 else if (sym
->aclass () == LOC_OPTIMIZED_OUT
)
1058 PyErr_Format (PyExc_RuntimeError
,
1059 _("Template argument is optimized out"));
1063 PyObject
*result
= nullptr;
1066 scoped_value_mark free_values
;
1067 struct value
*val
= value_of_variable (sym
, block
);
1068 result
= value_to_value_object (val
);
1070 catch (const gdb_exception
&except
)
1072 return gdbpy_handle_gdb_exception (nullptr, except
);
1078 /* __repr__ implementation for gdb.Type. */
1081 typy_repr (PyObject
*self
)
1083 const auto type
= type_object_to_type (self
);
1084 if (type
== nullptr)
1085 return gdb_py_invalid_object_repr (self
);
1087 const char *code
= pyty_codes
[type
->code ()].name
;
1088 string_file type_name
;
1091 current_language
->print_type (type
, "", &type_name
, -1, 0,
1092 &type_print_raw_options
);
1094 catch (const gdb_exception
&except
)
1096 return gdbpy_handle_gdb_exception (nullptr, except
);
1098 auto py_typename
= PyUnicode_Decode (type_name
.c_str (), type_name
.size (),
1099 host_charset (), NULL
);
1101 return PyUnicode_FromFormat ("<%s code=%s name=%U>", Py_TYPE (self
)->tp_name
,
1106 typy_str (PyObject
*self
)
1108 string_file thetype
;
1112 current_language
->print_type (type_object_to_type (self
), "",
1114 &type_print_raw_options
);
1116 catch (const gdb_exception
&except
)
1118 return gdbpy_handle_gdb_exception (nullptr, except
);
1121 return PyUnicode_Decode (thetype
.c_str (), thetype
.size (),
1122 host_charset (), NULL
);
1125 /* Implement the richcompare method. */
1128 typy_richcompare (PyObject
*self
, PyObject
*other
, int op
)
1130 bool result
= false;
1131 struct type
*type1
= type_object_to_type (self
);
1132 struct type
*type2
= type_object_to_type (other
);
1134 /* We can only compare ourselves to another Type object, and only
1135 for equality or inequality. */
1136 if (type2
== NULL
|| (op
!= Py_EQ
&& op
!= Py_NE
))
1138 Py_INCREF (Py_NotImplemented
);
1139 return Py_NotImplemented
;
1148 result
= types_deeply_equal (type1
, type2
);
1150 catch (const gdb_exception
&except
)
1152 /* If there is a GDB exception, a comparison is not capable
1153 (or trusted), so exit. */
1154 return gdbpy_handle_gdb_exception (nullptr, except
);
1158 if (op
== (result
? Py_EQ
: Py_NE
))
1165 /* Deleter that saves types when an objfile is being destroyed. */
1168 void operator() (type_object
*obj
)
1170 if (!gdb_python_initialized
)
1173 /* This prevents another thread from freeing the objects we're
1175 gdbpy_enter enter_py
;
1177 htab_up copied_types
= create_copied_types_hash ();
1181 type_object
*next
= obj
->next
;
1183 htab_empty (copied_types
.get ());
1185 obj
->type
= copy_type_recursive (obj
->type
, copied_types
.get ());
1195 static const registry
<objfile
>::key
<type_object
, typy_deleter
>
1196 typy_objfile_data_key
;
1199 set_type (type_object
*obj
, struct type
*type
)
1203 if (type
!= nullptr && type
->objfile_owner () != nullptr)
1205 struct objfile
*objfile
= type
->objfile_owner ();
1207 obj
->next
= typy_objfile_data_key
.get (objfile
);
1209 obj
->next
->prev
= obj
;
1210 typy_objfile_data_key
.set (objfile
, obj
);
1217 typy_dealloc (PyObject
*obj
)
1219 type_object
*type
= (type_object
*) obj
;
1222 type
->prev
->next
= type
->next
;
1223 else if (type
->type
!= nullptr && type
->type
->objfile_owner () != nullptr)
1225 /* Must reset head of list. */
1226 struct objfile
*objfile
= type
->type
->objfile_owner ();
1229 typy_objfile_data_key
.set (objfile
, type
->next
);
1232 type
->next
->prev
= type
->prev
;
1234 Py_TYPE (type
)->tp_free (type
);
1237 /* Return number of fields ("length" of the field dictionary). */
1240 typy_length (PyObject
*self
)
1242 struct type
*type
= ((type_object
*) self
)->type
;
1244 type
= typy_get_composite (type
);
1248 return type
->num_fields ();
1251 /* Implements boolean evaluation of gdb.Type. Handle this like other
1252 Python objects that don't have a meaningful truth value -- all
1256 typy_nonzero (PyObject
*self
)
1261 /* Return optimized out value of this type. */
1264 typy_optimized_out (PyObject
*self
, PyObject
*args
)
1266 struct type
*type
= ((type_object
*) self
)->type
;
1268 scoped_value_mark free_values
;
1269 return value_to_value_object (value::allocate_optimized_out (type
));
1272 /* Return a gdb.Field object for the field named by the argument. */
1275 typy_getitem (PyObject
*self
, PyObject
*key
)
1277 struct type
*type
= ((type_object
*) self
)->type
;
1280 gdb::unique_xmalloc_ptr
<char> field
= python_string_to_host_string (key
);
1284 /* We want just fields of this type, not of base types, so instead of
1285 using lookup_struct_elt_type, portions of that function are
1288 type
= typy_get_composite (type
);
1292 for (i
= 0; i
< type
->num_fields (); i
++)
1294 const char *t_field_name
= type
->field (i
).name ();
1296 if (t_field_name
&& (strcmp_iw (t_field_name
, field
.get ()) == 0))
1297 return convert_field (type
, i
).release ();
1299 PyErr_SetObject (PyExc_KeyError
, key
);
1303 /* Implement the "get" method on the type object. This is the
1304 same as getitem if the key is present, but returns the supplied
1305 default value or None if the key is not found. */
1308 typy_get (PyObject
*self
, PyObject
*args
)
1310 PyObject
*key
, *defval
= Py_None
, *result
;
1312 if (!PyArg_UnpackTuple (args
, "get", 1, 2, &key
, &defval
))
1315 result
= typy_getitem (self
, key
);
1319 /* typy_getitem returned error status. If the exception is
1320 KeyError, clear the exception status and return the defval
1321 instead. Otherwise return the exception unchanged. */
1322 if (!PyErr_ExceptionMatches (PyExc_KeyError
))
1330 /* Implement the "has_key" method on the type object. */
1333 typy_has_key (PyObject
*self
, PyObject
*args
)
1335 struct type
*type
= ((type_object
*) self
)->type
;
1339 if (!PyArg_ParseTuple (args
, "s", &field
))
1342 /* We want just fields of this type, not of base types, so instead of
1343 using lookup_struct_elt_type, portions of that function are
1346 type
= typy_get_composite (type
);
1350 for (i
= 0; i
< type
->num_fields (); i
++)
1352 const char *t_field_name
= type
->field (i
).name ();
1354 if (t_field_name
&& (strcmp_iw (t_field_name
, field
) == 0))
1360 /* Make an iterator object to iterate over keys, values, or items. */
1363 typy_make_iter (PyObject
*self
, enum gdbpy_iter_kind kind
)
1365 typy_iterator_object
*typy_iter_obj
;
1367 /* Check that "self" is a structure or union type. */
1368 if (typy_get_composite (((type_object
*) self
)->type
) == NULL
)
1371 typy_iter_obj
= PyObject_New (typy_iterator_object
,
1372 &type_iterator_object_type
);
1373 if (typy_iter_obj
== NULL
)
1376 typy_iter_obj
->field
= 0;
1377 typy_iter_obj
->kind
= kind
;
1379 typy_iter_obj
->source
= (type_object
*) self
;
1381 return (PyObject
*) typy_iter_obj
;
1384 /* iteritems() method. */
1387 typy_iteritems (PyObject
*self
, PyObject
*args
)
1389 return typy_make_iter (self
, iter_items
);
1392 /* iterkeys() method. */
1395 typy_iterkeys (PyObject
*self
, PyObject
*args
)
1397 return typy_make_iter (self
, iter_keys
);
1400 /* Iterating over the class, same as iterkeys except for the function
1404 typy_iter (PyObject
*self
)
1406 return typy_make_iter (self
, iter_keys
);
1409 /* itervalues() method. */
1412 typy_itervalues (PyObject
*self
, PyObject
*args
)
1414 return typy_make_iter (self
, iter_values
);
1417 /* Return a reference to the type iterator. */
1420 typy_iterator_iter (PyObject
*self
)
1426 /* Return the next field in the iteration through the list of fields
1430 typy_iterator_iternext (PyObject
*self
)
1432 typy_iterator_object
*iter_obj
= (typy_iterator_object
*) self
;
1433 struct type
*type
= iter_obj
->source
->type
;
1435 if (iter_obj
->field
< type
->num_fields ())
1437 gdbpy_ref
<> result
= make_fielditem (type
, iter_obj
->field
,
1441 return result
.release ();
1448 typy_iterator_dealloc (PyObject
*obj
)
1450 typy_iterator_object
*iter_obj
= (typy_iterator_object
*) obj
;
1452 Py_DECREF (iter_obj
->source
);
1453 Py_TYPE (obj
)->tp_free (obj
);
1456 /* Create a new Type referring to TYPE. */
1458 type_to_type_object (struct type
*type
)
1460 type_object
*type_obj
;
1464 /* Try not to let stub types leak out to Python. */
1465 if (type
->is_stub ())
1466 type
= check_typedef (type
);
1468 catch (const gdb_exception_error
&)
1470 /* Just ignore failures in check_typedef. */
1472 catch (const gdb_exception
&except
)
1474 return gdbpy_handle_gdb_exception (nullptr, except
);
1477 type_obj
= PyObject_New (type_object
, &type_object_type
);
1479 set_type (type_obj
, type
);
1481 return (PyObject
*) type_obj
;
1485 type_object_to_type (PyObject
*obj
)
1487 if (! PyObject_TypeCheck (obj
, &type_object_type
))
1489 return ((type_object
*) obj
)->type
;
1494 /* Implementation of gdb.lookup_type. */
1496 gdbpy_lookup_type (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
1498 static const char *keywords
[] = { "name", "block", NULL
};
1499 const char *type_name
= NULL
;
1500 struct type
*type
= NULL
;
1501 PyObject
*block_obj
= NULL
;
1502 const struct block
*block
= NULL
;
1504 if (!gdb_PyArg_ParseTupleAndKeywords (args
, kw
, "s|O", keywords
,
1505 &type_name
, &block_obj
))
1510 block
= block_object_to_block (block_obj
);
1513 PyErr_SetString (PyExc_RuntimeError
,
1514 _("'block' argument must be a Block."));
1519 type
= typy_lookup_typename (type_name
, block
);
1523 return type_to_type_object (type
);
1526 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
1527 gdbpy_initialize_types (void)
1529 if (gdbpy_type_ready (&type_object_type
) < 0)
1531 if (gdbpy_type_ready (&field_object_type
) < 0)
1533 if (gdbpy_type_ready (&type_iterator_object_type
) < 0)
1536 for (const auto &item
: pyty_codes
)
1538 if (PyModule_AddIntConstant (gdb_module
, item
.name
, item
.code
) < 0)
1545 GDBPY_INITIALIZE_FILE (gdbpy_initialize_types
);
1549 static gdb_PyGetSetDef type_object_getset
[] =
1551 { "alignof", typy_get_alignof
, NULL
,
1552 "The alignment of this type, in bytes.", NULL
},
1553 { "code", typy_get_code
, NULL
,
1554 "The code for this type.", NULL
},
1555 { "dynamic", typy_get_dynamic
, NULL
,
1556 "Whether this type is dynamic.", NULL
},
1557 { "name", typy_get_name
, NULL
,
1558 "The name for this type, or None.", NULL
},
1559 { "sizeof", typy_get_sizeof
, NULL
,
1560 "The size of this type, in bytes.", NULL
},
1561 { "tag", typy_get_tag
, NULL
,
1562 "The tag name for this type, or None.", NULL
},
1563 { "objfile", typy_get_objfile
, NULL
,
1564 "The objfile this type was defined in, or None.", NULL
},
1565 { "is_scalar", typy_is_scalar
, nullptr,
1566 "Is this a scalar type?", nullptr },
1567 { "is_signed", typy_is_signed
, nullptr,
1568 "Is this a signed type?", nullptr },
1569 { "is_array_like", typy_is_array_like
, nullptr,
1570 "Is this an array-like type?", nullptr },
1571 { "is_string_like", typy_is_string_like
, nullptr,
1572 "Is this a string-like type?", nullptr },
1576 static PyMethodDef type_object_methods
[] =
1578 { "array", typy_array
, METH_VARARGS
,
1579 "array ([LOW_BOUND,] HIGH_BOUND) -> Type\n\
1580 Return a type which represents an array of objects of this type.\n\
1581 The bounds of the array are [LOW_BOUND, HIGH_BOUND] inclusive.\n\
1582 If LOW_BOUND is omitted, a value of zero is used." },
1583 { "vector", typy_vector
, METH_VARARGS
,
1584 "vector ([LOW_BOUND,] HIGH_BOUND) -> Type\n\
1585 Return a type which represents a vector of objects of this type.\n\
1586 The bounds of the array are [LOW_BOUND, HIGH_BOUND] inclusive.\n\
1587 If LOW_BOUND is omitted, a value of zero is used.\n\
1588 Vectors differ from arrays in that if the current language has C-style\n\
1589 arrays, vectors don't decay to a pointer to the first element.\n\
1590 They are first class values." },
1591 { "__contains__", typy_has_key
, METH_VARARGS
,
1592 "T.__contains__(k) -> True if T has a field named k, else False" },
1593 { "const", typy_const
, METH_NOARGS
,
1594 "const () -> Type\n\
1595 Return a const variant of this type." },
1596 { "optimized_out", typy_optimized_out
, METH_NOARGS
,
1597 "optimized_out() -> Value\n\
1598 Return optimized out value of this type." },
1599 { "fields", typy_fields
, METH_NOARGS
,
1600 "fields () -> list\n\
1601 Return a list holding all the fields of this type.\n\
1602 Each field is a gdb.Field object." },
1603 { "get", typy_get
, METH_VARARGS
,
1604 "T.get(k[,default]) -> returns field named k in T, if it exists;\n\
1605 otherwise returns default, if supplied, or None if not." },
1606 { "has_key", typy_has_key
, METH_VARARGS
,
1607 "T.has_key(k) -> True if T has a field named k, else False" },
1608 { "items", typy_items
, METH_NOARGS
,
1609 "items () -> list\n\
1610 Return a list of (name, field) pairs of this type.\n\
1611 Each field is a gdb.Field object." },
1612 { "iteritems", typy_iteritems
, METH_NOARGS
,
1613 "iteritems () -> an iterator over the (name, field)\n\
1614 pairs of this type. Each field is a gdb.Field object." },
1615 { "iterkeys", typy_iterkeys
, METH_NOARGS
,
1616 "iterkeys () -> an iterator over the field names of this type." },
1617 { "itervalues", typy_itervalues
, METH_NOARGS
,
1618 "itervalues () -> an iterator over the fields of this type.\n\
1619 Each field is a gdb.Field object." },
1620 { "keys", typy_field_names
, METH_NOARGS
,
1622 Return a list holding all the fields names of this type." },
1623 { "pointer", typy_pointer
, METH_NOARGS
,
1624 "pointer () -> Type\n\
1625 Return a type of pointer to this type." },
1626 { "range", typy_range
, METH_NOARGS
,
1627 "range () -> tuple\n\
1628 Return a tuple containing the lower and upper range for this type."},
1629 { "reference", typy_reference
, METH_NOARGS
,
1630 "reference () -> Type\n\
1631 Return a type of reference to this type." },
1632 { "strip_typedefs", typy_strip_typedefs
, METH_NOARGS
,
1633 "strip_typedefs () -> Type\n\
1634 Return a type formed by stripping this type of all typedefs."},
1635 { "target", typy_target
, METH_NOARGS
,
1636 "target () -> Type\n\
1637 Return the target type of this type." },
1638 { "template_argument", typy_template_argument
, METH_VARARGS
,
1639 "template_argument (arg, [block]) -> Type\n\
1640 Return the type of a template argument." },
1641 { "unqualified", typy_unqualified
, METH_NOARGS
,
1642 "unqualified () -> Type\n\
1643 Return a variant of this type without const or volatile attributes." },
1644 { "values", typy_values
, METH_NOARGS
,
1645 "values () -> list\n\
1646 Return a list holding all the fields of this type.\n\
1647 Each field is a gdb.Field object." },
1648 { "volatile", typy_volatile
, METH_NOARGS
,
1649 "volatile () -> Type\n\
1650 Return a volatile variant of this type" },
1654 static PyNumberMethods type_object_as_number
= {
1656 NULL
, /* nb_subtract */
1657 NULL
, /* nb_multiply */
1658 NULL
, /* nb_remainder */
1659 NULL
, /* nb_divmod */
1660 NULL
, /* nb_power */
1661 NULL
, /* nb_negative */
1662 NULL
, /* nb_positive */
1663 NULL
, /* nb_absolute */
1664 typy_nonzero
, /* nb_nonzero */
1665 NULL
, /* nb_invert */
1666 NULL
, /* nb_lshift */
1667 NULL
, /* nb_rshift */
1672 NULL
, /* reserved */
1673 NULL
, /* nb_float */
1676 static PyMappingMethods typy_mapping
= {
1679 NULL
/* no "set" method */
1682 PyTypeObject type_object_type
=
1684 PyVarObject_HEAD_INIT (NULL
, 0)
1685 "gdb.Type", /*tp_name*/
1686 sizeof (type_object
), /*tp_basicsize*/
1688 typy_dealloc
, /*tp_dealloc*/
1693 typy_repr
, /*tp_repr*/
1694 &type_object_as_number
, /*tp_as_number*/
1695 0, /*tp_as_sequence*/
1696 &typy_mapping
, /*tp_as_mapping*/
1699 typy_str
, /*tp_str*/
1703 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
1704 "GDB type object", /* tp_doc */
1705 0, /* tp_traverse */
1707 typy_richcompare
, /* tp_richcompare */
1708 0, /* tp_weaklistoffset */
1709 typy_iter
, /* tp_iter */
1710 0, /* tp_iternext */
1711 type_object_methods
, /* tp_methods */
1713 type_object_getset
, /* tp_getset */
1716 0, /* tp_descr_get */
1717 0, /* tp_descr_set */
1718 0, /* tp_dictoffset */
1724 static gdb_PyGetSetDef field_object_getset
[] =
1726 { "__dict__", gdb_py_generic_dict
, NULL
,
1727 "The __dict__ for this field.", &field_object_type
},
1731 PyTypeObject field_object_type
=
1733 PyVarObject_HEAD_INIT (NULL
, 0)
1734 "gdb.Field", /*tp_name*/
1735 sizeof (field_object
), /*tp_basicsize*/
1737 field_dealloc
, /*tp_dealloc*/
1744 0, /*tp_as_sequence*/
1745 0, /*tp_as_mapping*/
1752 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
1753 "GDB field object", /* tp_doc */
1754 0, /* tp_traverse */
1756 0, /* tp_richcompare */
1757 0, /* tp_weaklistoffset */
1759 0, /* tp_iternext */
1762 field_object_getset
, /* tp_getset */
1765 0, /* tp_descr_get */
1766 0, /* tp_descr_set */
1767 offsetof (field_object
, dict
), /* tp_dictoffset */
1773 PyTypeObject type_iterator_object_type
= {
1774 PyVarObject_HEAD_INIT (NULL
, 0)
1775 "gdb.TypeIterator", /*tp_name*/
1776 sizeof (typy_iterator_object
), /*tp_basicsize*/
1778 typy_iterator_dealloc
, /*tp_dealloc*/
1785 0, /*tp_as_sequence*/
1786 0, /*tp_as_mapping*/
1793 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
1794 "GDB type iterator object", /*tp_doc */
1797 0, /*tp_richcompare */
1798 0, /*tp_weaklistoffset */
1799 typy_iterator_iter
, /*tp_iter */
1800 typy_iterator_iternext
, /*tp_iternext */