#ifndef Py_OBJECT_H1#define Py_OBJECT_H2#ifdef __cplusplus3extern "C" {4#endif567/* Object and type object interface */89/*10Objects are structures allocated on the heap. Special rules apply to11the use of objects to ensure they are properly garbage-collected.12Objects are never allocated statically or on the stack; they must be13accessed through special macros and functions only. (Type objects are14exceptions to the first rule; the standard types are represented by15statically initialized type objects, although work on type/class unification16for Python 2.2 made it possible to have heap-allocated type objects too).1718An object has a 'reference count' that is increased or decreased when a19pointer to the object is copied or deleted; when the reference count20reaches zero there are no references to the object left and it can be21removed from the heap.2223An object has a 'type' that determines what it represents and what kind24of data it contains. An object's type is fixed when it is created.25Types themselves are represented as objects; an object contains a26pointer to the corresponding type object. The type itself has a type27pointer pointing to the object representing the type 'type', which28contains a pointer to itself!.2930Objects do not float around in memory; once allocated an object keeps31the same size and address. Objects that must hold variable-size data32can contain pointers to variable-size parts of the object. Not all33objects of the same type have the same size; but the size cannot change34after allocation. (These restrictions are made so a reference to an35object can be simply a pointer -- moving an object would require36updating all the pointers, and changing an object's size would require37moving it if there was another object right next to it.)3839Objects are always accessed through pointers of the type 'PyObject *'.40The type 'PyObject' is a structure that only contains the reference count41and the type pointer. The actual memory allocated for an object42contains other data that can only be accessed after casting the pointer43to a pointer to a longer structure type. This longer type must start44with the reference count and type fields; the macro PyObject_HEAD should be45used for this (to accommodate for future changes). The implementation46of a particular object type can cast the object pointer to the proper47type and back.4849A standard interface exists for objects that contain an array of items50whose size is determined when the object is allocated.51*/5253#include "pystats.h"5455/* Py_DEBUG implies Py_REF_DEBUG. */56#if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)57# define Py_REF_DEBUG58#endif5960#if defined(Py_LIMITED_API) && defined(Py_TRACE_REFS)61# error Py_LIMITED_API is incompatible with Py_TRACE_REFS62#endif6364#ifdef Py_TRACE_REFS65/* Define pointers to support a doubly-linked list of all live heap objects. */66#define _PyObject_HEAD_EXTRA \67PyObject *_ob_next; \68PyObject *_ob_prev;6970#define _PyObject_EXTRA_INIT _Py_NULL, _Py_NULL,7172#else73# define _PyObject_HEAD_EXTRA74# define _PyObject_EXTRA_INIT75#endif7677/* PyObject_HEAD defines the initial segment of every PyObject. */78#define PyObject_HEAD PyObject ob_base;7980/*81Immortalization:8283The following indicates the immortalization strategy depending on the amount84of available bits in the reference count field. All strategies are backwards85compatible but the specific reference count value or immortalization check86might change depending on the specializations for the underlying system.8788Proper deallocation of immortal instances requires distinguishing between89statically allocated immortal instances vs those promoted by the runtime to be90immortal. The latter should be the only instances that require91cleanup during runtime finalization.92*/9394#if SIZEOF_VOID_P > 495/*96In 64+ bit systems, an object will be marked as immortal by setting all of the97lower 32 bits of the reference count field, which is equal to: 0xFFFFFFFF9899Using the lower 32 bits makes the value backwards compatible by allowing100C-Extensions without the updated checks in Py_INCREF and Py_DECREF to safely101increase and decrease the objects reference count. The object would lose its102immortality, but the execution would still be correct.103104Reference count increases will use saturated arithmetic, taking advantage of105having all the lower 32 bits set, which will avoid the reference count to go106beyond the refcount limit. Immortality checks for reference count decreases will107be done by checking the bit sign flag in the lower 32 bits.108*/109#define _Py_IMMORTAL_REFCNT UINT_MAX110111#else112/*113In 32 bit systems, an object will be marked as immortal by setting all of the114lower 30 bits of the reference count field, which is equal to: 0x3FFFFFFF115116Using the lower 30 bits makes the value backwards compatible by allowing117C-Extensions without the updated checks in Py_INCREF and Py_DECREF to safely118increase and decrease the objects reference count. The object would lose its119immortality, but the execution would still be correct.120121Reference count increases and decreases will first go through an immortality122check by comparing the reference count field to the immortality reference count.123*/124#define _Py_IMMORTAL_REFCNT (UINT_MAX >> 2)125#endif126127// Make all internal uses of PyObject_HEAD_INIT immortal while preserving the128// C-API expectation that the refcnt will be set to 1.129#ifdef Py_BUILD_CORE130#define PyObject_HEAD_INIT(type) \131{ \132_PyObject_EXTRA_INIT \133{ _Py_IMMORTAL_REFCNT }, \134(type) \135},136#else137#define PyObject_HEAD_INIT(type) \138{ \139_PyObject_EXTRA_INIT \140{ 1 }, \141(type) \142},143#endif /* Py_BUILD_CORE */144145#define PyVarObject_HEAD_INIT(type, size) \146{ \147PyObject_HEAD_INIT(type) \148(size) \149},150151/* PyObject_VAR_HEAD defines the initial segment of all variable-size152* container objects. These end with a declaration of an array with 1153* element, but enough space is malloc'ed so that the array actually154* has room for ob_size elements. Note that ob_size is an element count,155* not necessarily a byte count.156*/157#define PyObject_VAR_HEAD PyVarObject ob_base;158#define Py_INVALID_SIZE (Py_ssize_t)-1159160/* Nothing is actually declared to be a PyObject, but every pointer to161* a Python object can be cast to a PyObject*. This is inheritance built162* by hand. Similarly every pointer to a variable-size Python object can,163* in addition, be cast to PyVarObject*.164*/165struct _object {166_PyObject_HEAD_EXTRA167union {168Py_ssize_t ob_refcnt;169#if SIZEOF_VOID_P > 4170PY_UINT32_T ob_refcnt_split[2];171#endif172};173PyTypeObject *ob_type;174};175176/* Cast argument to PyObject* type. */177#define _PyObject_CAST(op) _Py_CAST(PyObject*, (op))178179typedef struct {180PyObject ob_base;181Py_ssize_t ob_size; /* Number of items in variable part */182} PyVarObject;183184/* Cast argument to PyVarObject* type. */185#define _PyVarObject_CAST(op) _Py_CAST(PyVarObject*, (op))186187188// Test if the 'x' object is the 'y' object, the same as "x is y" in Python.189PyAPI_FUNC(int) Py_Is(PyObject *x, PyObject *y);190#define Py_Is(x, y) ((x) == (y))191192193static inline Py_ssize_t Py_REFCNT(PyObject *ob) {194return ob->ob_refcnt;195}196#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000197# define Py_REFCNT(ob) Py_REFCNT(_PyObject_CAST(ob))198#endif199200201// bpo-39573: The Py_SET_TYPE() function must be used to set an object type.202static inline PyTypeObject* Py_TYPE(PyObject *ob) {203return ob->ob_type;204}205#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000206# define Py_TYPE(ob) Py_TYPE(_PyObject_CAST(ob))207#endif208209PyAPI_DATA(PyTypeObject) PyLong_Type;210PyAPI_DATA(PyTypeObject) PyBool_Type;211212// bpo-39573: The Py_SET_SIZE() function must be used to set an object size.213static inline Py_ssize_t Py_SIZE(PyObject *ob) {214assert(ob->ob_type != &PyLong_Type);215assert(ob->ob_type != &PyBool_Type);216PyVarObject *var_ob = _PyVarObject_CAST(ob);217return var_ob->ob_size;218}219#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000220# define Py_SIZE(ob) Py_SIZE(_PyObject_CAST(ob))221#endif222223static inline Py_ALWAYS_INLINE int _Py_IsImmortal(PyObject *op)224{225#if SIZEOF_VOID_P > 4226return _Py_CAST(PY_INT32_T, op->ob_refcnt) < 0;227#else228return op->ob_refcnt == _Py_IMMORTAL_REFCNT;229#endif230}231#define _Py_IsImmortal(op) _Py_IsImmortal(_PyObject_CAST(op))232233static inline int Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {234return Py_TYPE(ob) == type;235}236#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000237# define Py_IS_TYPE(ob, type) Py_IS_TYPE(_PyObject_CAST(ob), (type))238#endif239240241static inline void Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) {242// This immortal check is for code that is unaware of immortal objects.243// The runtime tracks these objects and we should avoid as much244// as possible having extensions inadvertently change the refcnt245// of an immortalized object.246if (_Py_IsImmortal(ob)) {247return;248}249ob->ob_refcnt = refcnt;250}251#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000252# define Py_SET_REFCNT(ob, refcnt) Py_SET_REFCNT(_PyObject_CAST(ob), (refcnt))253#endif254255256static inline void Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {257ob->ob_type = type;258}259#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000260# define Py_SET_TYPE(ob, type) Py_SET_TYPE(_PyObject_CAST(ob), type)261#endif262263static inline void Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {264assert(ob->ob_base.ob_type != &PyLong_Type);265assert(ob->ob_base.ob_type != &PyBool_Type);266ob->ob_size = size;267}268#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000269# define Py_SET_SIZE(ob, size) Py_SET_SIZE(_PyVarObject_CAST(ob), (size))270#endif271272273/*274Type objects contain a string containing the type name (to help somewhat275in debugging), the allocation parameters (see PyObject_New() and276PyObject_NewVar()),277and methods for accessing objects of the type. Methods are optional, a278nil pointer meaning that particular kind of access is not available for279this type. The Py_DECREF() macro uses the tp_dealloc method without280checking for a nil pointer; it should always be implemented except if281the implementation can guarantee that the reference count will never282reach zero (e.g., for statically allocated type objects).283284NB: the methods for certain type groups are now contained in separate285method blocks.286*/287288typedef PyObject * (*unaryfunc)(PyObject *);289typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);290typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);291typedef int (*inquiry)(PyObject *);292typedef Py_ssize_t (*lenfunc)(PyObject *);293typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);294typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);295typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);296typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);297typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);298299typedef int (*objobjproc)(PyObject *, PyObject *);300typedef int (*visitproc)(PyObject *, void *);301typedef int (*traverseproc)(PyObject *, visitproc, void *);302303304typedef void (*freefunc)(void *);305typedef void (*destructor)(PyObject *);306typedef PyObject *(*getattrfunc)(PyObject *, char *);307typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);308typedef int (*setattrfunc)(PyObject *, char *, PyObject *);309typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);310typedef PyObject *(*reprfunc)(PyObject *);311typedef Py_hash_t (*hashfunc)(PyObject *);312typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);313typedef PyObject *(*getiterfunc) (PyObject *);314typedef PyObject *(*iternextfunc) (PyObject *);315typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);316typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);317typedef int (*initproc)(PyObject *, PyObject *, PyObject *);318typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);319typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);320321#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030c0000 // 3.12322typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args,323size_t nargsf, PyObject *kwnames);324#endif325326typedef struct{327int slot; /* slot id, see below */328void *pfunc; /* function pointer */329} PyType_Slot;330331typedef struct{332const char* name;333int basicsize;334int itemsize;335unsigned int flags;336PyType_Slot *slots; /* terminated by slot==0. */337} PyType_Spec;338339PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);340#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000341PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);342#endif343#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000344PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);345#endif346#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000347PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);348PyAPI_FUNC(PyObject *) PyType_GetModule(PyTypeObject *);349PyAPI_FUNC(void *) PyType_GetModuleState(PyTypeObject *);350#endif351#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030B0000352PyAPI_FUNC(PyObject *) PyType_GetName(PyTypeObject *);353PyAPI_FUNC(PyObject *) PyType_GetQualName(PyTypeObject *);354#endif355#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030C0000356PyAPI_FUNC(PyObject *) PyType_FromMetaclass(PyTypeObject*, PyObject*, PyType_Spec*, PyObject*);357PyAPI_FUNC(void *) PyObject_GetTypeData(PyObject *obj, PyTypeObject *cls);358PyAPI_FUNC(Py_ssize_t) PyType_GetTypeDataSize(PyTypeObject *cls);359#endif360361/* Generic type check */362PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);363364static inline int PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {365return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);366}367#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000368# define PyObject_TypeCheck(ob, type) PyObject_TypeCheck(_PyObject_CAST(ob), (type))369#endif370371PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */372PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */373PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */374375PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);376377PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);378PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);379PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,380PyObject *, PyObject *);381PyAPI_FUNC(unsigned int) PyType_ClearCache(void);382PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);383384/* Generic operations on objects */385PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);386PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);387PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);388PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);389PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);390PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);391PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);392PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);393PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);394PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);395PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);396PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);397PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);398PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);399PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);400#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000401PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);402#endif403PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);404PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);405PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);406PyAPI_FUNC(int) PyObject_Not(PyObject *);407PyAPI_FUNC(int) PyCallable_Check(PyObject *);408PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);409410/* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a411list of strings. PyObject_Dir(NULL) is like builtins.dir(),412returning the names of the current locals. In this case, if there are413no current locals, NULL is returned, and PyErr_Occurred() is false.414*/415PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);416417/* Pickle support. */418#ifndef Py_LIMITED_API419PyAPI_FUNC(PyObject *) _PyObject_GetState(PyObject *);420#endif421422423/* Helpers for printing recursive container types */424PyAPI_FUNC(int) Py_ReprEnter(PyObject *);425PyAPI_FUNC(void) Py_ReprLeave(PyObject *);426427/* Flag bits for printing: */428#define Py_PRINT_RAW 1 /* No string quotes etc. */429430/*431Type flags (tp_flags)432433These flags are used to change expected features and behavior for a434particular type.435436Arbitration of the flag bit positions will need to be coordinated among437all extension writers who publicly release their extensions (this will438be fewer than you might expect!).439440Most flags were removed as of Python 3.0 to make room for new flags. (Some441flags are not for backwards compatibility but to indicate the presence of an442optional feature; these flags remain of course.)443444Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.445446Code can use PyType_HasFeature(type_ob, flag_value) to test whether the447given type object has a specified feature.448*/449450#ifndef Py_LIMITED_API451452/* Track types initialized using _PyStaticType_InitBuiltin(). */453#define _Py_TPFLAGS_STATIC_BUILTIN (1 << 1)454455/* Placement of weakref pointers are managed by the VM, not by the type.456* The VM will automatically set tp_weaklistoffset.457*/458#define Py_TPFLAGS_MANAGED_WEAKREF (1 << 3)459460/* Placement of dict (and values) pointers are managed by the VM, not by the type.461* The VM will automatically set tp_dictoffset.462*/463#define Py_TPFLAGS_MANAGED_DICT (1 << 4)464465#define Py_TPFLAGS_PREHEADER (Py_TPFLAGS_MANAGED_WEAKREF | Py_TPFLAGS_MANAGED_DICT)466467/* Set if instances of the type object are treated as sequences for pattern matching */468#define Py_TPFLAGS_SEQUENCE (1 << 5)469/* Set if instances of the type object are treated as mappings for pattern matching */470#define Py_TPFLAGS_MAPPING (1 << 6)471#endif472473/* Disallow creating instances of the type: set tp_new to NULL and don't create474* the "__new__" key in the type dictionary. */475#define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7)476477/* Set if the type object is immutable: type attributes cannot be set nor deleted */478#define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8)479480/* Set if the type object is dynamically allocated */481#define Py_TPFLAGS_HEAPTYPE (1UL << 9)482483/* Set if the type allows subclassing */484#define Py_TPFLAGS_BASETYPE (1UL << 10)485486/* Set if the type implements the vectorcall protocol (PEP 590) */487#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030C0000488#define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)489#ifndef Py_LIMITED_API490// Backwards compatibility alias for API that was provisional in Python 3.8491#define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL492#endif493#endif494495/* Set if the type is 'ready' -- fully initialized */496#define Py_TPFLAGS_READY (1UL << 12)497498/* Set while the type is being 'readied', to prevent recursive ready calls */499#define Py_TPFLAGS_READYING (1UL << 13)500501/* Objects support garbage collection (see objimpl.h) */502#define Py_TPFLAGS_HAVE_GC (1UL << 14)503504/* These two bits are preserved for Stackless Python, next after this is 17 */505#ifdef STACKLESS506#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)507#else508#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0509#endif510511/* Objects behave like an unbound method */512#define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)513514/* Object has up-to-date type attribute cache */515#define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19)516517/* Type is abstract and cannot be instantiated */518#define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)519520// This undocumented flag gives certain built-ins their unique pattern-matching521// behavior, which allows a single positional subpattern to match against the522// subject itself (rather than a mapped attribute on it):523#define _Py_TPFLAGS_MATCH_SELF (1UL << 22)524525/* Items (ob_size*tp_itemsize) are found at the end of an instance's memory */526#define Py_TPFLAGS_ITEMS_AT_END (1UL << 23)527528/* These flags are used to determine if a type is a subclass. */529#define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24)530#define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25)531#define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26)532#define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27)533#define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28)534#define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29)535#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30)536#define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31)537538#define Py_TPFLAGS_DEFAULT ( \539Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \5400)541542/* NOTE: Some of the following flags reuse lower bits (removed as part of the543* Python 3.0 transition). */544545/* The following flags are kept for compatibility; in previous546* versions they indicated presence of newer tp_* fields on the547* type struct.548* Starting with 3.8, binary compatibility of C extensions across549* feature releases of Python is not supported anymore (except when550* using the stable ABI, in which all classes are created dynamically,551* using the interpreter's memory layout.)552* Note that older extensions using the stable ABI set these flags,553* so the bits must not be repurposed.554*/555#define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)556#define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18)557558559/*560The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement561reference counts. Py_DECREF calls the object's deallocator function when562the refcount falls to 0; for563objects that don't contain references to other objects or heap memory564this can be the standard function free(). Both macros can be used565wherever a void expression is allowed. The argument must not be a566NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.567The macro _Py_NewReference(op) initialize reference counts to 1, and568in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional569bookkeeping appropriate to the special build.570571We assume that the reference count field can never overflow; this can572be proven when the size of the field is the same as the pointer size, so573we ignore the possibility. Provided a C int is at least 32 bits (which574is implicitly assumed in many parts of this code), that's enough for575about 2**31 references to an object.576577XXX The following became out of date in Python 2.2, but I'm not sure578XXX what the full truth is now. Certainly, heap-allocated type objects579XXX can and should be deallocated.580Type objects should never be deallocated; the type pointer in an object581is not considered to be a reference to the type object, to save582complications in the deallocation function. (This is actually a583decision that's up to the implementer of each new type so if you want,584you can count such references to the type object.)585*/586587#if defined(Py_REF_DEBUG) && !defined(Py_LIMITED_API)588PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,589PyObject *op);590PyAPI_FUNC(void) _Py_IncRefTotal_DO_NOT_USE_THIS(void);591PyAPI_FUNC(void) _Py_DecRefTotal_DO_NOT_USE_THIS(void);592# define _Py_INC_REFTOTAL() _Py_IncRefTotal_DO_NOT_USE_THIS()593# define _Py_DEC_REFTOTAL() _Py_DecRefTotal_DO_NOT_USE_THIS()594#endif // Py_REF_DEBUG && !Py_LIMITED_API595596PyAPI_FUNC(void) _Py_Dealloc(PyObject *);597598/*599These are provided as conveniences to Python runtime embedders, so that600they can have object code that is not dependent on Python compilation flags.601*/602PyAPI_FUNC(void) Py_IncRef(PyObject *);603PyAPI_FUNC(void) Py_DecRef(PyObject *);604605// Similar to Py_IncRef() and Py_DecRef() but the argument must be non-NULL.606// Private functions used by Py_INCREF() and Py_DECREF().607PyAPI_FUNC(void) _Py_IncRef(PyObject *);608PyAPI_FUNC(void) _Py_DecRef(PyObject *);609610static inline Py_ALWAYS_INLINE void Py_INCREF(PyObject *op)611{612#if defined(Py_LIMITED_API) && (Py_LIMITED_API+0 >= 0x030c0000 || defined(Py_REF_DEBUG))613// Stable ABI implements Py_INCREF() as a function call on limited C API614// version 3.12 and newer, and on Python built in debug mode. _Py_IncRef()615// was added to Python 3.10.0a7, use Py_IncRef() on older Python versions.616// Py_IncRef() accepts NULL whereas _Py_IncRef() doesn't.617# if Py_LIMITED_API+0 >= 0x030a00A7618_Py_IncRef(op);619# else620Py_IncRef(op);621# endif622#else623// Non-limited C API and limited C API for Python 3.9 and older access624// directly PyObject.ob_refcnt.625#if SIZEOF_VOID_P > 4626// Portable saturated add, branching on the carry flag and set low bits627PY_UINT32_T cur_refcnt = op->ob_refcnt_split[PY_BIG_ENDIAN];628PY_UINT32_T new_refcnt = cur_refcnt + 1;629if (new_refcnt == 0) {630return;631}632op->ob_refcnt_split[PY_BIG_ENDIAN] = new_refcnt;633#else634// Explicitly check immortality against the immortal value635if (_Py_IsImmortal(op)) {636return;637}638op->ob_refcnt++;639#endif640_Py_INCREF_STAT_INC();641#ifdef Py_REF_DEBUG642_Py_INC_REFTOTAL();643#endif644#endif645}646#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000647# define Py_INCREF(op) Py_INCREF(_PyObject_CAST(op))648#endif649650#if defined(Py_LIMITED_API) && (Py_LIMITED_API+0 >= 0x030c0000 || defined(Py_REF_DEBUG))651// Stable ABI implements Py_DECREF() as a function call on limited C API652// version 3.12 and newer, and on Python built in debug mode. _Py_DecRef() was653// added to Python 3.10.0a7, use Py_DecRef() on older Python versions.654// Py_DecRef() accepts NULL whereas _Py_IncRef() doesn't.655static inline void Py_DECREF(PyObject *op) {656# if Py_LIMITED_API+0 >= 0x030a00A7657_Py_DecRef(op);658# else659Py_DecRef(op);660# endif661}662#define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))663664#elif defined(Py_REF_DEBUG)665static inline void Py_DECREF(const char *filename, int lineno, PyObject *op)666{667if (_Py_IsImmortal(op)) {668return;669}670_Py_DECREF_STAT_INC();671_Py_DEC_REFTOTAL();672if (--op->ob_refcnt != 0) {673if (op->ob_refcnt < 0) {674_Py_NegativeRefcount(filename, lineno, op);675}676}677else {678_Py_Dealloc(op);679}680}681#define Py_DECREF(op) Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))682683#else684static inline Py_ALWAYS_INLINE void Py_DECREF(PyObject *op)685{686// Non-limited C API and limited C API for Python 3.9 and older access687// directly PyObject.ob_refcnt.688if (_Py_IsImmortal(op)) {689return;690}691_Py_DECREF_STAT_INC();692if (--op->ob_refcnt == 0) {693_Py_Dealloc(op);694}695}696#define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))697#endif698699#undef _Py_INC_REFTOTAL700#undef _Py_DEC_REFTOTAL701702703/* Safely decref `op` and set `op` to NULL, especially useful in tp_clear704* and tp_dealloc implementations.705*706* Note that "the obvious" code can be deadly:707*708* Py_XDECREF(op);709* op = NULL;710*711* Typically, `op` is something like self->containee, and `self` is done712* using its `containee` member. In the code sequence above, suppose713* `containee` is non-NULL with a refcount of 1. Its refcount falls to714* 0 on the first line, which can trigger an arbitrary amount of code,715* possibly including finalizers (like __del__ methods or weakref callbacks)716* coded in Python, which in turn can release the GIL and allow other threads717* to run, etc. Such code may even invoke methods of `self` again, or cause718* cyclic gc to trigger, but-- oops! --self->containee still points to the719* object being torn down, and it may be in an insane state while being torn720* down. This has in fact been a rich historic source of miserable (rare &721* hard-to-diagnose) segfaulting (and other) bugs.722*723* The safe way is:724*725* Py_CLEAR(op);726*727* That arranges to set `op` to NULL _before_ decref'ing, so that any code728* triggered as a side-effect of `op` getting torn down no longer believes729* `op` points to a valid object.730*731* There are cases where it's safe to use the naive code, but they're brittle.732* For example, if `op` points to a Python integer, you know that destroying733* one of those can't cause problems -- but in part that relies on that734* Python integers aren't currently weakly referencable. Best practice is735* to use Py_CLEAR() even if you can't think of a reason for why you need to.736*737* gh-98724: Use a temporary variable to only evaluate the macro argument once,738* to avoid the duplication of side effects if the argument has side effects.739*740* gh-99701: If the PyObject* type is used with casting arguments to PyObject*,741* the code can be miscompiled with strict aliasing because of type punning.742* With strict aliasing, a compiler considers that two pointers of different743* types cannot read or write the same memory which enables optimization744* opportunities.745*746* If available, use _Py_TYPEOF() to use the 'op' type for temporary variables,747* and so avoid type punning. Otherwise, use memcpy() which causes type erasure748* and so prevents the compiler to reuse an old cached 'op' value after749* Py_CLEAR().750*/751#ifdef _Py_TYPEOF752#define Py_CLEAR(op) \753do { \754_Py_TYPEOF(op)* _tmp_op_ptr = &(op); \755_Py_TYPEOF(op) _tmp_old_op = (*_tmp_op_ptr); \756if (_tmp_old_op != NULL) { \757*_tmp_op_ptr = _Py_NULL; \758Py_DECREF(_tmp_old_op); \759} \760} while (0)761#else762#define Py_CLEAR(op) \763do { \764PyObject **_tmp_op_ptr = _Py_CAST(PyObject**, &(op)); \765PyObject *_tmp_old_op = (*_tmp_op_ptr); \766if (_tmp_old_op != NULL) { \767PyObject *_null_ptr = _Py_NULL; \768memcpy(_tmp_op_ptr, &_null_ptr, sizeof(PyObject*)); \769Py_DECREF(_tmp_old_op); \770} \771} while (0)772#endif773774775/* Function to use in case the object pointer can be NULL: */776static inline void Py_XINCREF(PyObject *op)777{778if (op != _Py_NULL) {779Py_INCREF(op);780}781}782#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000783# define Py_XINCREF(op) Py_XINCREF(_PyObject_CAST(op))784#endif785786static inline void Py_XDECREF(PyObject *op)787{788if (op != _Py_NULL) {789Py_DECREF(op);790}791}792#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000793# define Py_XDECREF(op) Py_XDECREF(_PyObject_CAST(op))794#endif795796// Create a new strong reference to an object:797// increment the reference count of the object and return the object.798PyAPI_FUNC(PyObject*) Py_NewRef(PyObject *obj);799800// Similar to Py_NewRef(), but the object can be NULL.801PyAPI_FUNC(PyObject*) Py_XNewRef(PyObject *obj);802803static inline PyObject* _Py_NewRef(PyObject *obj)804{805Py_INCREF(obj);806return obj;807}808809static inline PyObject* _Py_XNewRef(PyObject *obj)810{811Py_XINCREF(obj);812return obj;813}814815// Py_NewRef() and Py_XNewRef() are exported as functions for the stable ABI.816// Names overridden with macros by static inline functions for best817// performances.818#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000819# define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))820# define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))821#else822# define Py_NewRef(obj) _Py_NewRef(obj)823# define Py_XNewRef(obj) _Py_XNewRef(obj)824#endif825826827/*828_Py_NoneStruct is an object of undefined type which can be used in contexts829where NULL (nil) is not suitable (since NULL often means 'error').830831Don't forget to apply Py_INCREF() when returning this value!!!832*/833PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */834#define Py_None (&_Py_NoneStruct)835836// Test if an object is the None singleton, the same as "x is None" in Python.837PyAPI_FUNC(int) Py_IsNone(PyObject *x);838#define Py_IsNone(x) Py_Is((x), Py_None)839840/* Macro for returning Py_None from a function */841#define Py_RETURN_NONE return Py_None842843/*844Py_NotImplemented is a singleton used to signal that an operation is845not implemented for a given type combination.846*/847PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */848#define Py_NotImplemented (&_Py_NotImplementedStruct)849850/* Macro for returning Py_NotImplemented from a function */851#define Py_RETURN_NOTIMPLEMENTED return Py_NotImplemented852853/* Rich comparison opcodes */854#define Py_LT 0855#define Py_LE 1856#define Py_EQ 2857#define Py_NE 3858#define Py_GT 4859#define Py_GE 5860861#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000862/* Result of calling PyIter_Send */863typedef enum {864PYGEN_RETURN = 0,865PYGEN_ERROR = -1,866PYGEN_NEXT = 1,867} PySendResult;868#endif869870/*871* Macro for implementing rich comparisons872*873* Needs to be a macro because any C-comparable type can be used.874*/875#define Py_RETURN_RICHCOMPARE(val1, val2, op) \876do { \877switch (op) { \878case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \879case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \880case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \881case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \882case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \883case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \884default: \885Py_UNREACHABLE(); \886} \887} while (0)888889890/*891More conventions892================893894Argument Checking895-----------------896897Functions that take objects as arguments normally don't check for nil898arguments, but they do check the type of the argument, and return an899error if the function doesn't apply to the type.900901Failure Modes902-------------903904Functions may fail for a variety of reasons, including running out of905memory. This is communicated to the caller in two ways: an error string906is set (see errors.h), and the function result differs: functions that907normally return a pointer return NULL for failure, functions returning908an integer return -1 (which could be a legal return value too!), and909other functions return 0 for success and -1 for failure.910Callers should always check for errors before using the result. If911an error was set, the caller must either explicitly clear it, or pass912the error on to its caller.913914Reference Counts915----------------916917It takes a while to get used to the proper usage of reference counts.918919Functions that create an object set the reference count to 1; such new920objects must be stored somewhere or destroyed again with Py_DECREF().921Some functions that 'store' objects, such as PyTuple_SetItem() and922PyList_SetItem(),923don't increment the reference count of the object, since the most924frequent use is to store a fresh object. Functions that 'retrieve'925objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also926don't increment927the reference count, since most frequently the object is only looked at928quickly. Thus, to retrieve an object and store it again, the caller929must call Py_INCREF() explicitly.930931NOTE: functions that 'consume' a reference count, like932PyList_SetItem(), consume the reference even if the object wasn't933successfully stored, to simplify error handling.934935It seems attractive to make other functions that take an object as936argument consume a reference count; however, this may quickly get937confusing (even the current practice is already confusing). Consider938it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at939times.940*/941942#ifndef Py_LIMITED_API943# define Py_CPYTHON_OBJECT_H944# include "cpython/object.h"945# undef Py_CPYTHON_OBJECT_H946#endif947948949static inline int950PyType_HasFeature(PyTypeObject *type, unsigned long feature)951{952unsigned long flags;953#ifdef Py_LIMITED_API954// PyTypeObject is opaque in the limited C API955flags = PyType_GetFlags(type);956#else957flags = type->tp_flags;958#endif959return ((flags & feature) != 0);960}961962#define PyType_FastSubclass(type, flag) PyType_HasFeature((type), (flag))963964static inline int PyType_Check(PyObject *op) {965return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);966}967#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000968# define PyType_Check(op) PyType_Check(_PyObject_CAST(op))969#endif970971#define _PyType_CAST(op) \972(assert(PyType_Check(op)), _Py_CAST(PyTypeObject*, (op)))973974static inline int PyType_CheckExact(PyObject *op) {975return Py_IS_TYPE(op, &PyType_Type);976}977#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000978# define PyType_CheckExact(op) PyType_CheckExact(_PyObject_CAST(op))979#endif980981#ifdef __cplusplus982}983#endif984#endif // !Py_OBJECT_H985986987