Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-11-19 09:50:54

0001 #ifndef Py_OBJECT_H
0002 #define Py_OBJECT_H
0003 #ifdef __cplusplus
0004 extern "C" {
0005 #endif
0006 
0007 
0008 /* Object and type object interface */
0009 
0010 /*
0011 Objects are structures allocated on the heap.  Special rules apply to
0012 the use of objects to ensure they are properly garbage-collected.
0013 Objects are never allocated statically or on the stack; they must be
0014 accessed through special macros and functions only.  (Type objects are
0015 exceptions to the first rule; the standard types are represented by
0016 statically initialized type objects, although work on type/class unification
0017 for Python 2.2 made it possible to have heap-allocated type objects too).
0018 
0019 An object has a 'reference count' that is increased or decreased when a
0020 pointer to the object is copied or deleted; when the reference count
0021 reaches zero there are no references to the object left and it can be
0022 removed from the heap.
0023 
0024 An object has a 'type' that determines what it represents and what kind
0025 of data it contains.  An object's type is fixed when it is created.
0026 Types themselves are represented as objects; an object contains a
0027 pointer to the corresponding type object.  The type itself has a type
0028 pointer pointing to the object representing the type 'type', which
0029 contains a pointer to itself!.
0030 
0031 Objects do not float around in memory; once allocated an object keeps
0032 the same size and address.  Objects that must hold variable-size data
0033 can contain pointers to variable-size parts of the object.  Not all
0034 objects of the same type have the same size; but the size cannot change
0035 after allocation.  (These restrictions are made so a reference to an
0036 object can be simply a pointer -- moving an object would require
0037 updating all the pointers, and changing an object's size would require
0038 moving it if there was another object right next to it.)
0039 
0040 Objects are always accessed through pointers of the type 'PyObject *'.
0041 The type 'PyObject' is a structure that only contains the reference count
0042 and the type pointer.  The actual memory allocated for an object
0043 contains other data that can only be accessed after casting the pointer
0044 to a pointer to a longer structure type.  This longer type must start
0045 with the reference count and type fields; the macro PyObject_HEAD should be
0046 used for this (to accommodate for future changes).  The implementation
0047 of a particular object type can cast the object pointer to the proper
0048 type and back.
0049 
0050 A standard interface exists for objects that contain an array of items
0051 whose size is determined when the object is allocated.
0052 */
0053 
0054 /* Py_DEBUG implies Py_REF_DEBUG. */
0055 #if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)
0056 #  define Py_REF_DEBUG
0057 #endif
0058 
0059 /* PyObject_HEAD defines the initial segment of every PyObject. */
0060 #define PyObject_HEAD                   PyObject ob_base;
0061 
0062 /*
0063 Immortalization:
0064 
0065 The following indicates the immortalization strategy depending on the amount
0066 of available bits in the reference count field. All strategies are backwards
0067 compatible but the specific reference count value or immortalization check
0068 might change depending on the specializations for the underlying system.
0069 
0070 Proper deallocation of immortal instances requires distinguishing between
0071 statically allocated immortal instances vs those promoted by the runtime to be
0072 immortal. The latter should be the only instances that require
0073 cleanup during runtime finalization.
0074 */
0075 
0076 #if SIZEOF_VOID_P > 4
0077 /*
0078 In 64+ bit systems, an object will be marked as immortal by setting all of the
0079 lower 32 bits of the reference count field, which is equal to: 0xFFFFFFFF
0080 
0081 Using the lower 32 bits makes the value backwards compatible by allowing
0082 C-Extensions without the updated checks in Py_INCREF and Py_DECREF to safely
0083 increase and decrease the objects reference count. The object would lose its
0084 immortality, but the execution would still be correct.
0085 
0086 Reference count increases will use saturated arithmetic, taking advantage of
0087 having all the lower 32 bits set, which will avoid the reference count to go
0088 beyond the refcount limit. Immortality checks for reference count decreases will
0089 be done by checking the bit sign flag in the lower 32 bits.
0090 */
0091 #define _Py_IMMORTAL_REFCNT _Py_CAST(Py_ssize_t, UINT_MAX)
0092 
0093 #else
0094 /*
0095 In 32 bit systems, an object will be marked as immortal by setting all of the
0096 lower 30 bits of the reference count field, which is equal to: 0x3FFFFFFF
0097 
0098 Using the lower 30 bits makes the value backwards compatible by allowing
0099 C-Extensions without the updated checks in Py_INCREF and Py_DECREF to safely
0100 increase and decrease the objects reference count. The object would lose its
0101 immortality, but the execution would still be correct.
0102 
0103 Reference count increases and decreases will first go through an immortality
0104 check by comparing the reference count field to the immortality reference count.
0105 */
0106 #define _Py_IMMORTAL_REFCNT _Py_CAST(Py_ssize_t, UINT_MAX >> 2)
0107 #endif
0108 
0109 // Py_GIL_DISABLED builds indicate immortal objects using `ob_ref_local`, which is
0110 // always 32-bits.
0111 #ifdef Py_GIL_DISABLED
0112 #define _Py_IMMORTAL_REFCNT_LOCAL UINT32_MAX
0113 #endif
0114 
0115 // Kept for backward compatibility. It was needed by Py_TRACE_REFS build.
0116 #define _PyObject_EXTRA_INIT
0117 
0118 /* Make all uses of PyObject_HEAD_INIT immortal.
0119  *
0120  * Statically allocated objects might be shared between
0121  * interpreters, so must be marked as immortal.
0122  */
0123 #if defined(Py_GIL_DISABLED)
0124 #define PyObject_HEAD_INIT(type)    \
0125     {                               \
0126         0,                          \
0127         0,                          \
0128         { 0 },                      \
0129         0,                          \
0130         _Py_IMMORTAL_REFCNT_LOCAL,  \
0131         0,                          \
0132         (type),                     \
0133     },
0134 #else
0135 #define PyObject_HEAD_INIT(type)    \
0136     {                               \
0137         { _Py_IMMORTAL_REFCNT },    \
0138         (type)                      \
0139     },
0140 #endif
0141 
0142 #define PyVarObject_HEAD_INIT(type, size) \
0143     {                                     \
0144         PyObject_HEAD_INIT(type)          \
0145         (size)                            \
0146     },
0147 
0148 /* PyObject_VAR_HEAD defines the initial segment of all variable-size
0149  * container objects.  These end with a declaration of an array with 1
0150  * element, but enough space is malloc'ed so that the array actually
0151  * has room for ob_size elements.  Note that ob_size is an element count,
0152  * not necessarily a byte count.
0153  */
0154 #define PyObject_VAR_HEAD      PyVarObject ob_base;
0155 #define Py_INVALID_SIZE (Py_ssize_t)-1
0156 
0157 /* Nothing is actually declared to be a PyObject, but every pointer to
0158  * a Python object can be cast to a PyObject*.  This is inheritance built
0159  * by hand.  Similarly every pointer to a variable-size Python object can,
0160  * in addition, be cast to PyVarObject*.
0161  */
0162 #ifndef Py_GIL_DISABLED
0163 struct _object {
0164 #if (defined(__GNUC__) || defined(__clang__)) \
0165         && !(defined __STDC_VERSION__ && __STDC_VERSION__ >= 201112L)
0166     // On C99 and older, anonymous union is a GCC and clang extension
0167     __extension__
0168 #endif
0169 #ifdef _MSC_VER
0170     // Ignore MSC warning C4201: "nonstandard extension used:
0171     // nameless struct/union"
0172     __pragma(warning(push))
0173     __pragma(warning(disable: 4201))
0174 #endif
0175     union {
0176        Py_ssize_t ob_refcnt;
0177 #if SIZEOF_VOID_P > 4
0178        PY_UINT32_T ob_refcnt_split[2];
0179 #endif
0180     };
0181 #ifdef _MSC_VER
0182     __pragma(warning(pop))
0183 #endif
0184 
0185     PyTypeObject *ob_type;
0186 };
0187 #else
0188 // Objects that are not owned by any thread use a thread id (tid) of zero.
0189 // This includes both immortal objects and objects whose reference count
0190 // fields have been merged.
0191 #define _Py_UNOWNED_TID             0
0192 
0193 // The shared reference count uses the two least-significant bits to store
0194 // flags. The remaining bits are used to store the reference count.
0195 #define _Py_REF_SHARED_SHIFT        2
0196 #define _Py_REF_SHARED_FLAG_MASK    0x3
0197 
0198 // The shared flags are initialized to zero.
0199 #define _Py_REF_SHARED_INIT         0x0
0200 #define _Py_REF_MAYBE_WEAKREF       0x1
0201 #define _Py_REF_QUEUED              0x2
0202 #define _Py_REF_MERGED              0x3
0203 
0204 // Create a shared field from a refcnt and desired flags
0205 #define _Py_REF_SHARED(refcnt, flags) (((refcnt) << _Py_REF_SHARED_SHIFT) + (flags))
0206 
0207 struct _object {
0208     // ob_tid stores the thread id (or zero). It is also used by the GC and the
0209     // trashcan mechanism as a linked list pointer and by the GC to store the
0210     // computed "gc_refs" refcount.
0211     uintptr_t ob_tid;
0212     uint16_t _padding;
0213     PyMutex ob_mutex;           // per-object lock
0214     uint8_t ob_gc_bits;         // gc-related state
0215     uint32_t ob_ref_local;      // local reference count
0216     Py_ssize_t ob_ref_shared;   // shared (atomic) reference count
0217     PyTypeObject *ob_type;
0218 };
0219 #endif
0220 
0221 /* Cast argument to PyObject* type. */
0222 #define _PyObject_CAST(op) _Py_CAST(PyObject*, (op))
0223 
0224 typedef struct {
0225     PyObject ob_base;
0226     Py_ssize_t ob_size; /* Number of items in variable part */
0227 } PyVarObject;
0228 
0229 /* Cast argument to PyVarObject* type. */
0230 #define _PyVarObject_CAST(op) _Py_CAST(PyVarObject*, (op))
0231 
0232 
0233 // Test if the 'x' object is the 'y' object, the same as "x is y" in Python.
0234 PyAPI_FUNC(int) Py_Is(PyObject *x, PyObject *y);
0235 #define Py_Is(x, y) ((x) == (y))
0236 
0237 #if defined(Py_GIL_DISABLED) && !defined(Py_LIMITED_API)
0238 PyAPI_FUNC(uintptr_t) _Py_GetThreadLocal_Addr(void);
0239 
0240 static inline uintptr_t
0241 _Py_ThreadId(void)
0242 {
0243     uintptr_t tid;
0244 #if defined(_MSC_VER) && defined(_M_X64)
0245     tid = __readgsqword(48);
0246 #elif defined(_MSC_VER) && defined(_M_IX86)
0247     tid = __readfsdword(24);
0248 #elif defined(_MSC_VER) && defined(_M_ARM64)
0249     tid = __getReg(18);
0250 #elif defined(__MINGW32__) && defined(_M_X64)
0251     tid = __readgsqword(48);
0252 #elif defined(__MINGW32__) && defined(_M_IX86)
0253     tid = __readfsdword(24);
0254 #elif defined(__MINGW32__) && defined(_M_ARM64)
0255     tid = __getReg(18);
0256 #elif defined(__i386__)
0257     __asm__("movl %%gs:0, %0" : "=r" (tid));  // 32-bit always uses GS
0258 #elif defined(__MACH__) && defined(__x86_64__)
0259     __asm__("movq %%gs:0, %0" : "=r" (tid));  // x86_64 macOSX uses GS
0260 #elif defined(__x86_64__)
0261    __asm__("movq %%fs:0, %0" : "=r" (tid));  // x86_64 Linux, BSD uses FS
0262 #elif defined(__arm__) && __ARM_ARCH >= 7
0263     __asm__ ("mrc p15, 0, %0, c13, c0, 3\nbic %0, %0, #3" : "=r" (tid));
0264 #elif defined(__aarch64__) && defined(__APPLE__)
0265     __asm__ ("mrs %0, tpidrro_el0" : "=r" (tid));
0266 #elif defined(__aarch64__)
0267     __asm__ ("mrs %0, tpidr_el0" : "=r" (tid));
0268 #elif defined(__powerpc64__)
0269     #if defined(__clang__) && _Py__has_builtin(__builtin_thread_pointer)
0270     tid = (uintptr_t)__builtin_thread_pointer();
0271     #else
0272     // r13 is reserved for use as system thread ID by the Power 64-bit ABI.
0273     register uintptr_t tp __asm__ ("r13");
0274     __asm__("" : "=r" (tp));
0275     tid = tp;
0276     #endif
0277 #elif defined(__powerpc__)
0278     #if defined(__clang__) && _Py__has_builtin(__builtin_thread_pointer)
0279     tid = (uintptr_t)__builtin_thread_pointer();
0280     #else
0281     // r2 is reserved for use as system thread ID by the Power 32-bit ABI.
0282     register uintptr_t tp __asm__ ("r2");
0283     __asm__ ("" : "=r" (tp));
0284     tid = tp;
0285     #endif
0286 #elif defined(__s390__) && defined(__GNUC__)
0287     // Both GCC and Clang have supported __builtin_thread_pointer
0288     // for s390 from long time ago.
0289     tid = (uintptr_t)__builtin_thread_pointer();
0290 #elif defined(__riscv)
0291     #if defined(__clang__) && _Py__has_builtin(__builtin_thread_pointer)
0292     tid = (uintptr_t)__builtin_thread_pointer();
0293     #else
0294     // tp is Thread Pointer provided by the RISC-V ABI.
0295     __asm__ ("mv %0, tp" : "=r" (tid));
0296     #endif
0297 #else
0298     // Fallback to a portable implementation if we do not have a faster
0299     // platform-specific implementation.
0300     tid = _Py_GetThreadLocal_Addr();
0301 #endif
0302   return tid;
0303 }
0304 
0305 static inline Py_ALWAYS_INLINE int
0306 _Py_IsOwnedByCurrentThread(PyObject *ob)
0307 {
0308 #ifdef _Py_THREAD_SANITIZER
0309     return _Py_atomic_load_uintptr_relaxed(&ob->ob_tid) == _Py_ThreadId();
0310 #else
0311     return ob->ob_tid == _Py_ThreadId();
0312 #endif
0313 }
0314 #endif
0315 
0316 static inline Py_ssize_t Py_REFCNT(PyObject *ob) {
0317 #if !defined(Py_GIL_DISABLED)
0318     return ob->ob_refcnt;
0319 #else
0320     uint32_t local = _Py_atomic_load_uint32_relaxed(&ob->ob_ref_local);
0321     if (local == _Py_IMMORTAL_REFCNT_LOCAL) {
0322         return _Py_IMMORTAL_REFCNT;
0323     }
0324     Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&ob->ob_ref_shared);
0325     return _Py_STATIC_CAST(Py_ssize_t, local) +
0326            Py_ARITHMETIC_RIGHT_SHIFT(Py_ssize_t, shared, _Py_REF_SHARED_SHIFT);
0327 #endif
0328 }
0329 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0330 #  define Py_REFCNT(ob) Py_REFCNT(_PyObject_CAST(ob))
0331 #endif
0332 
0333 
0334 // bpo-39573: The Py_SET_TYPE() function must be used to set an object type.
0335 static inline PyTypeObject* Py_TYPE(PyObject *ob) {
0336     return ob->ob_type;
0337 }
0338 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0339 #  define Py_TYPE(ob) Py_TYPE(_PyObject_CAST(ob))
0340 #endif
0341 
0342 PyAPI_DATA(PyTypeObject) PyLong_Type;
0343 PyAPI_DATA(PyTypeObject) PyBool_Type;
0344 
0345 // bpo-39573: The Py_SET_SIZE() function must be used to set an object size.
0346 static inline Py_ssize_t Py_SIZE(PyObject *ob) {
0347     assert(ob->ob_type != &PyLong_Type);
0348     assert(ob->ob_type != &PyBool_Type);
0349     return  _PyVarObject_CAST(ob)->ob_size;
0350 }
0351 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0352 #  define Py_SIZE(ob) Py_SIZE(_PyObject_CAST(ob))
0353 #endif
0354 
0355 static inline Py_ALWAYS_INLINE int _Py_IsImmortal(PyObject *op)
0356 {
0357 #if defined(Py_GIL_DISABLED)
0358     return (_Py_atomic_load_uint32_relaxed(&op->ob_ref_local) ==
0359             _Py_IMMORTAL_REFCNT_LOCAL);
0360 #elif SIZEOF_VOID_P > 4
0361     return (_Py_CAST(PY_INT32_T, op->ob_refcnt) < 0);
0362 #else
0363     return (op->ob_refcnt == _Py_IMMORTAL_REFCNT);
0364 #endif
0365 }
0366 #define _Py_IsImmortal(op) _Py_IsImmortal(_PyObject_CAST(op))
0367 
0368 static inline int Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {
0369     return Py_TYPE(ob) == type;
0370 }
0371 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0372 #  define Py_IS_TYPE(ob, type) Py_IS_TYPE(_PyObject_CAST(ob), (type))
0373 #endif
0374 
0375 
0376 // Py_SET_REFCNT() implementation for stable ABI
0377 PyAPI_FUNC(void) _Py_SetRefcnt(PyObject *ob, Py_ssize_t refcnt);
0378 
0379 static inline void Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) {
0380 #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030d0000
0381     // Stable ABI implements Py_SET_REFCNT() as a function call
0382     // on limited C API version 3.13 and newer.
0383     _Py_SetRefcnt(ob, refcnt);
0384 #else
0385     // This immortal check is for code that is unaware of immortal objects.
0386     // The runtime tracks these objects and we should avoid as much
0387     // as possible having extensions inadvertently change the refcnt
0388     // of an immortalized object.
0389     if (_Py_IsImmortal(ob)) {
0390         return;
0391     }
0392 
0393 #ifndef Py_GIL_DISABLED
0394     ob->ob_refcnt = refcnt;
0395 #else
0396     if (_Py_IsOwnedByCurrentThread(ob)) {
0397         if ((size_t)refcnt > (size_t)UINT32_MAX) {
0398             // On overflow, make the object immortal
0399             ob->ob_tid = _Py_UNOWNED_TID;
0400             ob->ob_ref_local = _Py_IMMORTAL_REFCNT_LOCAL;
0401             ob->ob_ref_shared = 0;
0402         }
0403         else {
0404             // Set local refcount to desired refcount and shared refcount
0405             // to zero, but preserve the shared refcount flags.
0406             ob->ob_ref_local = _Py_STATIC_CAST(uint32_t, refcnt);
0407             ob->ob_ref_shared &= _Py_REF_SHARED_FLAG_MASK;
0408         }
0409     }
0410     else {
0411         // Set local refcount to zero and shared refcount to desired refcount.
0412         // Mark the object as merged.
0413         ob->ob_tid = _Py_UNOWNED_TID;
0414         ob->ob_ref_local = 0;
0415         ob->ob_ref_shared = _Py_REF_SHARED(refcnt, _Py_REF_MERGED);
0416     }
0417 #endif  // Py_GIL_DISABLED
0418 #endif  // Py_LIMITED_API+0 < 0x030d0000
0419 }
0420 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0421 #  define Py_SET_REFCNT(ob, refcnt) Py_SET_REFCNT(_PyObject_CAST(ob), (refcnt))
0422 #endif
0423 
0424 
0425 static inline void Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {
0426     ob->ob_type = type;
0427 }
0428 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0429 #  define Py_SET_TYPE(ob, type) Py_SET_TYPE(_PyObject_CAST(ob), type)
0430 #endif
0431 
0432 static inline void Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
0433     assert(ob->ob_base.ob_type != &PyLong_Type);
0434     assert(ob->ob_base.ob_type != &PyBool_Type);
0435 #ifdef Py_GIL_DISABLED
0436     _Py_atomic_store_ssize_relaxed(&ob->ob_size, size);
0437 #else
0438     ob->ob_size = size;
0439 #endif
0440 }
0441 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0442 #  define Py_SET_SIZE(ob, size) Py_SET_SIZE(_PyVarObject_CAST(ob), (size))
0443 #endif
0444 
0445 
0446 /*
0447 Type objects contain a string containing the type name (to help somewhat
0448 in debugging), the allocation parameters (see PyObject_New() and
0449 PyObject_NewVar()),
0450 and methods for accessing objects of the type.  Methods are optional, a
0451 nil pointer meaning that particular kind of access is not available for
0452 this type.  The Py_DECREF() macro uses the tp_dealloc method without
0453 checking for a nil pointer; it should always be implemented except if
0454 the implementation can guarantee that the reference count will never
0455 reach zero (e.g., for statically allocated type objects).
0456 
0457 NB: the methods for certain type groups are now contained in separate
0458 method blocks.
0459 */
0460 
0461 typedef PyObject * (*unaryfunc)(PyObject *);
0462 typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
0463 typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
0464 typedef int (*inquiry)(PyObject *);
0465 typedef Py_ssize_t (*lenfunc)(PyObject *);
0466 typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
0467 typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
0468 typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
0469 typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
0470 typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
0471 
0472 typedef int (*objobjproc)(PyObject *, PyObject *);
0473 typedef int (*visitproc)(PyObject *, void *);
0474 typedef int (*traverseproc)(PyObject *, visitproc, void *);
0475 
0476 
0477 typedef void (*freefunc)(void *);
0478 typedef void (*destructor)(PyObject *);
0479 typedef PyObject *(*getattrfunc)(PyObject *, char *);
0480 typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
0481 typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
0482 typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
0483 typedef PyObject *(*reprfunc)(PyObject *);
0484 typedef Py_hash_t (*hashfunc)(PyObject *);
0485 typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
0486 typedef PyObject *(*getiterfunc) (PyObject *);
0487 typedef PyObject *(*iternextfunc) (PyObject *);
0488 typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
0489 typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
0490 typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
0491 typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);
0492 typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);
0493 
0494 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030c0000 // 3.12
0495 typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args,
0496                                     size_t nargsf, PyObject *kwnames);
0497 #endif
0498 
0499 typedef struct{
0500     int slot;    /* slot id, see below */
0501     void *pfunc; /* function pointer */
0502 } PyType_Slot;
0503 
0504 typedef struct{
0505     const char* name;
0506     int basicsize;
0507     int itemsize;
0508     unsigned int flags;
0509     PyType_Slot *slots; /* terminated by slot==0. */
0510 } PyType_Spec;
0511 
0512 PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
0513 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
0514 PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);
0515 #endif
0516 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
0517 PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);
0518 #endif
0519 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
0520 PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);
0521 PyAPI_FUNC(PyObject *) PyType_GetModule(PyTypeObject *);
0522 PyAPI_FUNC(void *) PyType_GetModuleState(PyTypeObject *);
0523 #endif
0524 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030B0000
0525 PyAPI_FUNC(PyObject *) PyType_GetName(PyTypeObject *);
0526 PyAPI_FUNC(PyObject *) PyType_GetQualName(PyTypeObject *);
0527 #endif
0528 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030D0000
0529 PyAPI_FUNC(PyObject *) PyType_GetFullyQualifiedName(PyTypeObject *type);
0530 PyAPI_FUNC(PyObject *) PyType_GetModuleName(PyTypeObject *type);
0531 #endif
0532 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030C0000
0533 PyAPI_FUNC(PyObject *) PyType_FromMetaclass(PyTypeObject*, PyObject*, PyType_Spec*, PyObject*);
0534 PyAPI_FUNC(void *) PyObject_GetTypeData(PyObject *obj, PyTypeObject *cls);
0535 PyAPI_FUNC(Py_ssize_t) PyType_GetTypeDataSize(PyTypeObject *cls);
0536 #endif
0537 
0538 /* Generic type check */
0539 PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
0540 
0541 static inline int PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {
0542     return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);
0543 }
0544 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0545 #  define PyObject_TypeCheck(ob, type) PyObject_TypeCheck(_PyObject_CAST(ob), (type))
0546 #endif
0547 
0548 PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
0549 PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
0550 PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
0551 
0552 PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);
0553 
0554 PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
0555 PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
0556 PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
0557                                                PyObject *, PyObject *);
0558 PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
0559 PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
0560 
0561 /* Generic operations on objects */
0562 PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
0563 PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
0564 PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
0565 PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
0566 PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
0567 PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
0568 PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
0569 PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
0570 PyAPI_FUNC(int) PyObject_DelAttrString(PyObject *v, const char *name);
0571 PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
0572 PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
0573 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000
0574 PyAPI_FUNC(int) PyObject_GetOptionalAttr(PyObject *, PyObject *, PyObject **);
0575 PyAPI_FUNC(int) PyObject_GetOptionalAttrString(PyObject *, const char *, PyObject **);
0576 #endif
0577 PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
0578 PyAPI_FUNC(int) PyObject_DelAttr(PyObject *v, PyObject *name);
0579 PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
0580 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000
0581 PyAPI_FUNC(int) PyObject_HasAttrWithError(PyObject *, PyObject *);
0582 PyAPI_FUNC(int) PyObject_HasAttrStringWithError(PyObject *, const char *);
0583 #endif
0584 PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
0585 PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
0586 PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);
0587 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
0588 PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
0589 #endif
0590 PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
0591 PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
0592 PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
0593 PyAPI_FUNC(int) PyObject_Not(PyObject *);
0594 PyAPI_FUNC(int) PyCallable_Check(PyObject *);
0595 PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
0596 
0597 /* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
0598    list of strings.  PyObject_Dir(NULL) is like builtins.dir(),
0599    returning the names of the current locals.  In this case, if there are
0600    no current locals, NULL is returned, and PyErr_Occurred() is false.
0601 */
0602 PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
0603 
0604 /* Helpers for printing recursive container types */
0605 PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
0606 PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
0607 
0608 /* Flag bits for printing: */
0609 #define Py_PRINT_RAW    1       /* No string quotes etc. */
0610 
0611 /*
0612 Type flags (tp_flags)
0613 
0614 These flags are used to change expected features and behavior for a
0615 particular type.
0616 
0617 Arbitration of the flag bit positions will need to be coordinated among
0618 all extension writers who publicly release their extensions (this will
0619 be fewer than you might expect!).
0620 
0621 Most flags were removed as of Python 3.0 to make room for new flags.  (Some
0622 flags are not for backwards compatibility but to indicate the presence of an
0623 optional feature; these flags remain of course.)
0624 
0625 Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
0626 
0627 Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
0628 given type object has a specified feature.
0629 */
0630 
0631 #ifndef Py_LIMITED_API
0632 
0633 /* Track types initialized using _PyStaticType_InitBuiltin(). */
0634 #define _Py_TPFLAGS_STATIC_BUILTIN (1 << 1)
0635 
0636 /* The values array is placed inline directly after the rest of
0637  * the object. Implies Py_TPFLAGS_HAVE_GC.
0638  */
0639 #define Py_TPFLAGS_INLINE_VALUES (1 << 2)
0640 
0641 /* Placement of weakref pointers are managed by the VM, not by the type.
0642  * The VM will automatically set tp_weaklistoffset.
0643  */
0644 #define Py_TPFLAGS_MANAGED_WEAKREF (1 << 3)
0645 
0646 /* Placement of dict (and values) pointers are managed by the VM, not by the type.
0647  * The VM will automatically set tp_dictoffset. Implies Py_TPFLAGS_HAVE_GC.
0648  */
0649 #define Py_TPFLAGS_MANAGED_DICT (1 << 4)
0650 
0651 #define Py_TPFLAGS_PREHEADER (Py_TPFLAGS_MANAGED_WEAKREF | Py_TPFLAGS_MANAGED_DICT)
0652 
0653 /* Set if instances of the type object are treated as sequences for pattern matching */
0654 #define Py_TPFLAGS_SEQUENCE (1 << 5)
0655 /* Set if instances of the type object are treated as mappings for pattern matching */
0656 #define Py_TPFLAGS_MAPPING (1 << 6)
0657 #endif
0658 
0659 /* Disallow creating instances of the type: set tp_new to NULL and don't create
0660  * the "__new__" key in the type dictionary. */
0661 #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7)
0662 
0663 /* Set if the type object is immutable: type attributes cannot be set nor deleted */
0664 #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8)
0665 
0666 /* Set if the type object is dynamically allocated */
0667 #define Py_TPFLAGS_HEAPTYPE (1UL << 9)
0668 
0669 /* Set if the type allows subclassing */
0670 #define Py_TPFLAGS_BASETYPE (1UL << 10)
0671 
0672 /* Set if the type implements the vectorcall protocol (PEP 590) */
0673 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030C0000
0674 #define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)
0675 #ifndef Py_LIMITED_API
0676 // Backwards compatibility alias for API that was provisional in Python 3.8
0677 #define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL
0678 #endif
0679 #endif
0680 
0681 /* Set if the type is 'ready' -- fully initialized */
0682 #define Py_TPFLAGS_READY (1UL << 12)
0683 
0684 /* Set while the type is being 'readied', to prevent recursive ready calls */
0685 #define Py_TPFLAGS_READYING (1UL << 13)
0686 
0687 /* Objects support garbage collection (see objimpl.h) */
0688 #define Py_TPFLAGS_HAVE_GC (1UL << 14)
0689 
0690 /* These two bits are preserved for Stackless Python, next after this is 17 */
0691 #ifdef STACKLESS
0692 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)
0693 #else
0694 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
0695 #endif
0696 
0697 /* Objects behave like an unbound method */
0698 #define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
0699 
0700 /* Unused. Legacy flag */
0701 #define Py_TPFLAGS_VALID_VERSION_TAG  (1UL << 19)
0702 
0703 /* Type is abstract and cannot be instantiated */
0704 #define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)
0705 
0706 // This undocumented flag gives certain built-ins their unique pattern-matching
0707 // behavior, which allows a single positional subpattern to match against the
0708 // subject itself (rather than a mapped attribute on it):
0709 #define _Py_TPFLAGS_MATCH_SELF (1UL << 22)
0710 
0711 /* Items (ob_size*tp_itemsize) are found at the end of an instance's memory */
0712 #define Py_TPFLAGS_ITEMS_AT_END (1UL << 23)
0713 
0714 /* These flags are used to determine if a type is a subclass. */
0715 #define Py_TPFLAGS_LONG_SUBCLASS        (1UL << 24)
0716 #define Py_TPFLAGS_LIST_SUBCLASS        (1UL << 25)
0717 #define Py_TPFLAGS_TUPLE_SUBCLASS       (1UL << 26)
0718 #define Py_TPFLAGS_BYTES_SUBCLASS       (1UL << 27)
0719 #define Py_TPFLAGS_UNICODE_SUBCLASS     (1UL << 28)
0720 #define Py_TPFLAGS_DICT_SUBCLASS        (1UL << 29)
0721 #define Py_TPFLAGS_BASE_EXC_SUBCLASS    (1UL << 30)
0722 #define Py_TPFLAGS_TYPE_SUBCLASS        (1UL << 31)
0723 
0724 #define Py_TPFLAGS_DEFAULT  ( \
0725                  Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
0726                 0)
0727 
0728 /* NOTE: Some of the following flags reuse lower bits (removed as part of the
0729  * Python 3.0 transition). */
0730 
0731 /* The following flags are kept for compatibility; in previous
0732  * versions they indicated presence of newer tp_* fields on the
0733  * type struct.
0734  * Starting with 3.8, binary compatibility of C extensions across
0735  * feature releases of Python is not supported anymore (except when
0736  * using the stable ABI, in which all classes are created dynamically,
0737  * using the interpreter's memory layout.)
0738  * Note that older extensions using the stable ABI set these flags,
0739  * so the bits must not be repurposed.
0740  */
0741 #define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)
0742 #define Py_TPFLAGS_HAVE_VERSION_TAG   (1UL << 18)
0743 
0744 
0745 /*
0746 The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
0747 reference counts.  Py_DECREF calls the object's deallocator function when
0748 the refcount falls to 0; for
0749 objects that don't contain references to other objects or heap memory
0750 this can be the standard function free().  Both macros can be used
0751 wherever a void expression is allowed.  The argument must not be a
0752 NULL pointer.  If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
0753 The macro _Py_NewReference(op) initialize reference counts to 1, and
0754 in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
0755 bookkeeping appropriate to the special build.
0756 
0757 We assume that the reference count field can never overflow; this can
0758 be proven when the size of the field is the same as the pointer size, so
0759 we ignore the possibility.  Provided a C int is at least 32 bits (which
0760 is implicitly assumed in many parts of this code), that's enough for
0761 about 2**31 references to an object.
0762 
0763 XXX The following became out of date in Python 2.2, but I'm not sure
0764 XXX what the full truth is now.  Certainly, heap-allocated type objects
0765 XXX can and should be deallocated.
0766 Type objects should never be deallocated; the type pointer in an object
0767 is not considered to be a reference to the type object, to save
0768 complications in the deallocation function.  (This is actually a
0769 decision that's up to the implementer of each new type so if you want,
0770 you can count such references to the type object.)
0771 */
0772 
0773 #if defined(Py_REF_DEBUG) && !defined(Py_LIMITED_API)
0774 PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
0775                                       PyObject *op);
0776 PyAPI_FUNC(void) _Py_INCREF_IncRefTotal(void);
0777 PyAPI_FUNC(void) _Py_DECREF_DecRefTotal(void);
0778 #endif  // Py_REF_DEBUG && !Py_LIMITED_API
0779 
0780 PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
0781 
0782 /*
0783 These are provided as conveniences to Python runtime embedders, so that
0784 they can have object code that is not dependent on Python compilation flags.
0785 */
0786 PyAPI_FUNC(void) Py_IncRef(PyObject *);
0787 PyAPI_FUNC(void) Py_DecRef(PyObject *);
0788 
0789 // Similar to Py_IncRef() and Py_DecRef() but the argument must be non-NULL.
0790 // Private functions used by Py_INCREF() and Py_DECREF().
0791 PyAPI_FUNC(void) _Py_IncRef(PyObject *);
0792 PyAPI_FUNC(void) _Py_DecRef(PyObject *);
0793 
0794 static inline Py_ALWAYS_INLINE void Py_INCREF(PyObject *op)
0795 {
0796 #if defined(Py_LIMITED_API) && (Py_LIMITED_API+0 >= 0x030c0000 || defined(Py_REF_DEBUG))
0797     // Stable ABI implements Py_INCREF() as a function call on limited C API
0798     // version 3.12 and newer, and on Python built in debug mode. _Py_IncRef()
0799     // was added to Python 3.10.0a7, use Py_IncRef() on older Python versions.
0800     // Py_IncRef() accepts NULL whereas _Py_IncRef() doesn't.
0801 #  if Py_LIMITED_API+0 >= 0x030a00A7
0802     _Py_IncRef(op);
0803 #  else
0804     Py_IncRef(op);
0805 #  endif
0806 #else
0807     // Non-limited C API and limited C API for Python 3.9 and older access
0808     // directly PyObject.ob_refcnt.
0809 #if defined(Py_GIL_DISABLED)
0810     uint32_t local = _Py_atomic_load_uint32_relaxed(&op->ob_ref_local);
0811     uint32_t new_local = local + 1;
0812     if (new_local == 0) {
0813         // local is equal to _Py_IMMORTAL_REFCNT: do nothing
0814         return;
0815     }
0816     if (_Py_IsOwnedByCurrentThread(op)) {
0817         _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, new_local);
0818     }
0819     else {
0820         _Py_atomic_add_ssize(&op->ob_ref_shared, (1 << _Py_REF_SHARED_SHIFT));
0821     }
0822 #elif SIZEOF_VOID_P > 4
0823     // Portable saturated add, branching on the carry flag and set low bits
0824     PY_UINT32_T cur_refcnt = op->ob_refcnt_split[PY_BIG_ENDIAN];
0825     PY_UINT32_T new_refcnt = cur_refcnt + 1;
0826     if (new_refcnt == 0) {
0827         // cur_refcnt is equal to _Py_IMMORTAL_REFCNT: the object is immortal,
0828         // do nothing
0829         return;
0830     }
0831     op->ob_refcnt_split[PY_BIG_ENDIAN] = new_refcnt;
0832 #else
0833     // Explicitly check immortality against the immortal value
0834     if (_Py_IsImmortal(op)) {
0835         return;
0836     }
0837     op->ob_refcnt++;
0838 #endif
0839     _Py_INCREF_STAT_INC();
0840 #ifdef Py_REF_DEBUG
0841     _Py_INCREF_IncRefTotal();
0842 #endif
0843 #endif
0844 }
0845 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
0846 #  define Py_INCREF(op) Py_INCREF(_PyObject_CAST(op))
0847 #endif
0848 
0849 
0850 #if !defined(Py_LIMITED_API) && defined(Py_GIL_DISABLED)
0851 // Implements Py_DECREF on objects not owned by the current thread.
0852 PyAPI_FUNC(void) _Py_DecRefShared(PyObject *);
0853 PyAPI_FUNC(void) _Py_DecRefSharedDebug(PyObject *, const char *, int);
0854 
0855 // Called from Py_DECREF by the owning thread when the local refcount reaches
0856 // zero. The call will deallocate the object if the shared refcount is also
0857 // zero. Otherwise, the thread gives up ownership and merges the reference
0858 // count fields.
0859 PyAPI_FUNC(void) _Py_MergeZeroLocalRefcount(PyObject *);
0860 #endif
0861 
0862 #if defined(Py_LIMITED_API) && (Py_LIMITED_API+0 >= 0x030c0000 || defined(Py_REF_DEBUG))
0863 // Stable ABI implements Py_DECREF() as a function call on limited C API
0864 // version 3.12 and newer, and on Python built in debug mode. _Py_DecRef() was
0865 // added to Python 3.10.0a7, use Py_DecRef() on older Python versions.
0866 // Py_DecRef() accepts NULL whereas _Py_IncRef() doesn't.
0867 static inline void Py_DECREF(PyObject *op) {
0868 #  if Py_LIMITED_API+0 >= 0x030a00A7
0869     _Py_DecRef(op);
0870 #  else
0871     Py_DecRef(op);
0872 #  endif
0873 }
0874 #define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
0875 
0876 #elif defined(Py_GIL_DISABLED) && defined(Py_REF_DEBUG)
0877 static inline void Py_DECREF(const char *filename, int lineno, PyObject *op)
0878 {
0879     uint32_t local = _Py_atomic_load_uint32_relaxed(&op->ob_ref_local);
0880     if (local == _Py_IMMORTAL_REFCNT_LOCAL) {
0881         return;
0882     }
0883     _Py_DECREF_STAT_INC();
0884     _Py_DECREF_DecRefTotal();
0885     if (_Py_IsOwnedByCurrentThread(op)) {
0886         if (local == 0) {
0887             _Py_NegativeRefcount(filename, lineno, op);
0888         }
0889         local--;
0890         _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, local);
0891         if (local == 0) {
0892             _Py_MergeZeroLocalRefcount(op);
0893         }
0894     }
0895     else {
0896         _Py_DecRefSharedDebug(op, filename, lineno);
0897     }
0898 }
0899 #define Py_DECREF(op) Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
0900 
0901 #elif defined(Py_GIL_DISABLED)
0902 static inline void Py_DECREF(PyObject *op)
0903 {
0904     uint32_t local = _Py_atomic_load_uint32_relaxed(&op->ob_ref_local);
0905     if (local == _Py_IMMORTAL_REFCNT_LOCAL) {
0906         return;
0907     }
0908     _Py_DECREF_STAT_INC();
0909     if (_Py_IsOwnedByCurrentThread(op)) {
0910         local--;
0911         _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, local);
0912         if (local == 0) {
0913             _Py_MergeZeroLocalRefcount(op);
0914         }
0915     }
0916     else {
0917         _Py_DecRefShared(op);
0918     }
0919 }
0920 #define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
0921 
0922 #elif defined(Py_REF_DEBUG)
0923 static inline void Py_DECREF(const char *filename, int lineno, PyObject *op)
0924 {
0925     if (op->ob_refcnt <= 0) {
0926         _Py_NegativeRefcount(filename, lineno, op);
0927     }
0928     if (_Py_IsImmortal(op)) {
0929         return;
0930     }
0931     _Py_DECREF_STAT_INC();
0932     _Py_DECREF_DecRefTotal();
0933     if (--op->ob_refcnt == 0) {
0934         _Py_Dealloc(op);
0935     }
0936 }
0937 #define Py_DECREF(op) Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
0938 
0939 #else
0940 static inline Py_ALWAYS_INLINE void Py_DECREF(PyObject *op)
0941 {
0942     // Non-limited C API and limited C API for Python 3.9 and older access
0943     // directly PyObject.ob_refcnt.
0944     if (_Py_IsImmortal(op)) {
0945         return;
0946     }
0947     _Py_DECREF_STAT_INC();
0948     if (--op->ob_refcnt == 0) {
0949         _Py_Dealloc(op);
0950     }
0951 }
0952 #define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
0953 #endif
0954 
0955 
0956 /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
0957  * and tp_dealloc implementations.
0958  *
0959  * Note that "the obvious" code can be deadly:
0960  *
0961  *     Py_XDECREF(op);
0962  *     op = NULL;
0963  *
0964  * Typically, `op` is something like self->containee, and `self` is done
0965  * using its `containee` member.  In the code sequence above, suppose
0966  * `containee` is non-NULL with a refcount of 1.  Its refcount falls to
0967  * 0 on the first line, which can trigger an arbitrary amount of code,
0968  * possibly including finalizers (like __del__ methods or weakref callbacks)
0969  * coded in Python, which in turn can release the GIL and allow other threads
0970  * to run, etc.  Such code may even invoke methods of `self` again, or cause
0971  * cyclic gc to trigger, but-- oops! --self->containee still points to the
0972  * object being torn down, and it may be in an insane state while being torn
0973  * down.  This has in fact been a rich historic source of miserable (rare &
0974  * hard-to-diagnose) segfaulting (and other) bugs.
0975  *
0976  * The safe way is:
0977  *
0978  *      Py_CLEAR(op);
0979  *
0980  * That arranges to set `op` to NULL _before_ decref'ing, so that any code
0981  * triggered as a side-effect of `op` getting torn down no longer believes
0982  * `op` points to a valid object.
0983  *
0984  * There are cases where it's safe to use the naive code, but they're brittle.
0985  * For example, if `op` points to a Python integer, you know that destroying
0986  * one of those can't cause problems -- but in part that relies on that
0987  * Python integers aren't currently weakly referencable.  Best practice is
0988  * to use Py_CLEAR() even if you can't think of a reason for why you need to.
0989  *
0990  * gh-98724: Use a temporary variable to only evaluate the macro argument once,
0991  * to avoid the duplication of side effects if the argument has side effects.
0992  *
0993  * gh-99701: If the PyObject* type is used with casting arguments to PyObject*,
0994  * the code can be miscompiled with strict aliasing because of type punning.
0995  * With strict aliasing, a compiler considers that two pointers of different
0996  * types cannot read or write the same memory which enables optimization
0997  * opportunities.
0998  *
0999  * If available, use _Py_TYPEOF() to use the 'op' type for temporary variables,
1000  * and so avoid type punning. Otherwise, use memcpy() which causes type erasure
1001  * and so prevents the compiler to reuse an old cached 'op' value after
1002  * Py_CLEAR().
1003  */
1004 #ifdef _Py_TYPEOF
1005 #define Py_CLEAR(op) \
1006     do { \
1007         _Py_TYPEOF(op)* _tmp_op_ptr = &(op); \
1008         _Py_TYPEOF(op) _tmp_old_op = (*_tmp_op_ptr); \
1009         if (_tmp_old_op != NULL) { \
1010             *_tmp_op_ptr = _Py_NULL; \
1011             Py_DECREF(_tmp_old_op); \
1012         } \
1013     } while (0)
1014 #else
1015 #define Py_CLEAR(op) \
1016     do { \
1017         PyObject **_tmp_op_ptr = _Py_CAST(PyObject**, &(op)); \
1018         PyObject *_tmp_old_op = (*_tmp_op_ptr); \
1019         if (_tmp_old_op != NULL) { \
1020             PyObject *_null_ptr = _Py_NULL; \
1021             memcpy(_tmp_op_ptr, &_null_ptr, sizeof(PyObject*)); \
1022             Py_DECREF(_tmp_old_op); \
1023         } \
1024     } while (0)
1025 #endif
1026 
1027 
1028 /* Function to use in case the object pointer can be NULL: */
1029 static inline void Py_XINCREF(PyObject *op)
1030 {
1031     if (op != _Py_NULL) {
1032         Py_INCREF(op);
1033     }
1034 }
1035 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
1036 #  define Py_XINCREF(op) Py_XINCREF(_PyObject_CAST(op))
1037 #endif
1038 
1039 static inline void Py_XDECREF(PyObject *op)
1040 {
1041     if (op != _Py_NULL) {
1042         Py_DECREF(op);
1043     }
1044 }
1045 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
1046 #  define Py_XDECREF(op) Py_XDECREF(_PyObject_CAST(op))
1047 #endif
1048 
1049 // Create a new strong reference to an object:
1050 // increment the reference count of the object and return the object.
1051 PyAPI_FUNC(PyObject*) Py_NewRef(PyObject *obj);
1052 
1053 // Similar to Py_NewRef(), but the object can be NULL.
1054 PyAPI_FUNC(PyObject*) Py_XNewRef(PyObject *obj);
1055 
1056 static inline PyObject* _Py_NewRef(PyObject *obj)
1057 {
1058     Py_INCREF(obj);
1059     return obj;
1060 }
1061 
1062 static inline PyObject* _Py_XNewRef(PyObject *obj)
1063 {
1064     Py_XINCREF(obj);
1065     return obj;
1066 }
1067 
1068 // Py_NewRef() and Py_XNewRef() are exported as functions for the stable ABI.
1069 // Names overridden with macros by static inline functions for best
1070 // performances.
1071 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
1072 #  define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))
1073 #  define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))
1074 #else
1075 #  define Py_NewRef(obj) _Py_NewRef(obj)
1076 #  define Py_XNewRef(obj) _Py_XNewRef(obj)
1077 #endif
1078 
1079 
1080 #define Py_CONSTANT_NONE 0
1081 #define Py_CONSTANT_FALSE 1
1082 #define Py_CONSTANT_TRUE 2
1083 #define Py_CONSTANT_ELLIPSIS 3
1084 #define Py_CONSTANT_NOT_IMPLEMENTED 4
1085 #define Py_CONSTANT_ZERO 5
1086 #define Py_CONSTANT_ONE 6
1087 #define Py_CONSTANT_EMPTY_STR 7
1088 #define Py_CONSTANT_EMPTY_BYTES 8
1089 #define Py_CONSTANT_EMPTY_TUPLE 9
1090 
1091 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000
1092 PyAPI_FUNC(PyObject*) Py_GetConstant(unsigned int constant_id);
1093 PyAPI_FUNC(PyObject*) Py_GetConstantBorrowed(unsigned int constant_id);
1094 #endif
1095 
1096 
1097 /*
1098 _Py_NoneStruct is an object of undefined type which can be used in contexts
1099 where NULL (nil) is not suitable (since NULL often means 'error').
1100 */
1101 PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
1102 
1103 #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030D0000
1104 #  define Py_None Py_GetConstantBorrowed(Py_CONSTANT_NONE)
1105 #else
1106 #  define Py_None (&_Py_NoneStruct)
1107 #endif
1108 
1109 // Test if an object is the None singleton, the same as "x is None" in Python.
1110 PyAPI_FUNC(int) Py_IsNone(PyObject *x);
1111 #define Py_IsNone(x) Py_Is((x), Py_None)
1112 
1113 /* Macro for returning Py_None from a function.
1114  * Only treat Py_None as immortal in the limited C API 3.12 and newer. */
1115 #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 < 0x030c0000
1116 #  define Py_RETURN_NONE return Py_NewRef(Py_None)
1117 #else
1118 #  define Py_RETURN_NONE return Py_None
1119 #endif
1120 
1121 /*
1122 Py_NotImplemented is a singleton used to signal that an operation is
1123 not implemented for a given type combination.
1124 */
1125 PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
1126 
1127 #if defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030D0000
1128 #  define Py_NotImplemented Py_GetConstantBorrowed(Py_CONSTANT_NOT_IMPLEMENTED)
1129 #else
1130 #  define Py_NotImplemented (&_Py_NotImplementedStruct)
1131 #endif
1132 
1133 /* Macro for returning Py_NotImplemented from a function */
1134 #define Py_RETURN_NOTIMPLEMENTED return Py_NotImplemented
1135 
1136 /* Rich comparison opcodes */
1137 #define Py_LT 0
1138 #define Py_LE 1
1139 #define Py_EQ 2
1140 #define Py_NE 3
1141 #define Py_GT 4
1142 #define Py_GE 5
1143 
1144 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
1145 /* Result of calling PyIter_Send */
1146 typedef enum {
1147     PYGEN_RETURN = 0,
1148     PYGEN_ERROR = -1,
1149     PYGEN_NEXT = 1,
1150 } PySendResult;
1151 #endif
1152 
1153 /*
1154  * Macro for implementing rich comparisons
1155  *
1156  * Needs to be a macro because any C-comparable type can be used.
1157  */
1158 #define Py_RETURN_RICHCOMPARE(val1, val2, op)                               \
1159     do {                                                                    \
1160         switch (op) {                                                       \
1161         case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;  \
1162         case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;  \
1163         case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;   \
1164         case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;   \
1165         case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;  \
1166         case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE;  \
1167         default:                                                            \
1168             Py_UNREACHABLE();                                               \
1169         }                                                                   \
1170     } while (0)
1171 
1172 
1173 /*
1174 More conventions
1175 ================
1176 
1177 Argument Checking
1178 -----------------
1179 
1180 Functions that take objects as arguments normally don't check for nil
1181 arguments, but they do check the type of the argument, and return an
1182 error if the function doesn't apply to the type.
1183 
1184 Failure Modes
1185 -------------
1186 
1187 Functions may fail for a variety of reasons, including running out of
1188 memory.  This is communicated to the caller in two ways: an error string
1189 is set (see errors.h), and the function result differs: functions that
1190 normally return a pointer return NULL for failure, functions returning
1191 an integer return -1 (which could be a legal return value too!), and
1192 other functions return 0 for success and -1 for failure.
1193 Callers should always check for errors before using the result.  If
1194 an error was set, the caller must either explicitly clear it, or pass
1195 the error on to its caller.
1196 
1197 Reference Counts
1198 ----------------
1199 
1200 It takes a while to get used to the proper usage of reference counts.
1201 
1202 Functions that create an object set the reference count to 1; such new
1203 objects must be stored somewhere or destroyed again with Py_DECREF().
1204 Some functions that 'store' objects, such as PyTuple_SetItem() and
1205 PyList_SetItem(),
1206 don't increment the reference count of the object, since the most
1207 frequent use is to store a fresh object.  Functions that 'retrieve'
1208 objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
1209 don't increment
1210 the reference count, since most frequently the object is only looked at
1211 quickly.  Thus, to retrieve an object and store it again, the caller
1212 must call Py_INCREF() explicitly.
1213 
1214 NOTE: functions that 'consume' a reference count, like
1215 PyList_SetItem(), consume the reference even if the object wasn't
1216 successfully stored, to simplify error handling.
1217 
1218 It seems attractive to make other functions that take an object as
1219 argument consume a reference count; however, this may quickly get
1220 confusing (even the current practice is already confusing).  Consider
1221 it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
1222 times.
1223 */
1224 
1225 #ifndef Py_LIMITED_API
1226 #  define Py_CPYTHON_OBJECT_H
1227 #  include "cpython/object.h"
1228 #  undef Py_CPYTHON_OBJECT_H
1229 #endif
1230 
1231 
1232 static inline int
1233 PyType_HasFeature(PyTypeObject *type, unsigned long feature)
1234 {
1235     unsigned long flags;
1236 #ifdef Py_LIMITED_API
1237     // PyTypeObject is opaque in the limited C API
1238     flags = PyType_GetFlags(type);
1239 #else
1240 #   ifdef Py_GIL_DISABLED
1241         flags = _Py_atomic_load_ulong_relaxed(&type->tp_flags);
1242 #   else
1243         flags = type->tp_flags;
1244 #   endif
1245 #endif
1246     return ((flags & feature) != 0);
1247 }
1248 
1249 #define PyType_FastSubclass(type, flag) PyType_HasFeature((type), (flag))
1250 
1251 static inline int PyType_Check(PyObject *op) {
1252     return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);
1253 }
1254 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
1255 #  define PyType_Check(op) PyType_Check(_PyObject_CAST(op))
1256 #endif
1257 
1258 #define _PyType_CAST(op) \
1259     (assert(PyType_Check(op)), _Py_CAST(PyTypeObject*, (op)))
1260 
1261 static inline int PyType_CheckExact(PyObject *op) {
1262     return Py_IS_TYPE(op, &PyType_Type);
1263 }
1264 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
1265 #  define PyType_CheckExact(op) PyType_CheckExact(_PyObject_CAST(op))
1266 #endif
1267 
1268 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030d0000
1269 PyAPI_FUNC(PyObject *) PyType_GetModuleByDef(PyTypeObject *, PyModuleDef *);
1270 #endif
1271 
1272 #ifdef __cplusplus
1273 }
1274 #endif
1275 #endif   // !Py_OBJECT_H