Back to home page

EIC code displayed by LXR

 
 

    


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

0001 #ifndef Py_CPYTHON_OBJECT_H
0002 #  error "this header file must not be included directly"
0003 #endif
0004 
0005 PyAPI_FUNC(void) _Py_NewReference(PyObject *op);
0006 PyAPI_FUNC(void) _Py_NewReferenceNoTotal(PyObject *op);
0007 PyAPI_FUNC(void) _Py_ResurrectReference(PyObject *op);
0008 
0009 #ifdef Py_REF_DEBUG
0010 /* These are useful as debugging aids when chasing down refleaks. */
0011 PyAPI_FUNC(Py_ssize_t) _Py_GetGlobalRefTotal(void);
0012 #  define _Py_GetRefTotal() _Py_GetGlobalRefTotal()
0013 PyAPI_FUNC(Py_ssize_t) _Py_GetLegacyRefTotal(void);
0014 PyAPI_FUNC(Py_ssize_t) _PyInterpreterState_GetRefTotal(PyInterpreterState *);
0015 #endif
0016 
0017 
0018 /********************* String Literals ****************************************/
0019 /* This structure helps managing static strings. The basic usage goes like this:
0020    Instead of doing
0021 
0022        r = PyObject_CallMethod(o, "foo", "args", ...);
0023 
0024    do
0025 
0026        _Py_IDENTIFIER(foo);
0027        ...
0028        r = _PyObject_CallMethodId(o, &PyId_foo, "args", ...);
0029 
0030    PyId_foo is a static variable, either on block level or file level. On first
0031    usage, the string "foo" is interned, and the structures are linked. On interpreter
0032    shutdown, all strings are released.
0033 
0034    Alternatively, _Py_static_string allows choosing the variable name.
0035    _PyUnicode_FromId returns a borrowed reference to the interned string.
0036    _PyObject_{Get,Set,Has}AttrId are __getattr__ versions using _Py_Identifier*.
0037 */
0038 typedef struct _Py_Identifier {
0039     const char* string;
0040     // Index in PyInterpreterState.unicode.ids.array. It is process-wide
0041     // unique and must be initialized to -1.
0042     Py_ssize_t index;
0043     // Hidden PyMutex struct for non free-threaded build.
0044     struct {
0045         uint8_t v;
0046     } mutex;
0047 } _Py_Identifier;
0048 
0049 #ifndef Py_BUILD_CORE
0050 // For now we are keeping _Py_IDENTIFIER for continued use
0051 // in non-builtin extensions (and naughty PyPI modules).
0052 
0053 #define _Py_static_string_init(value) { .string = (value), .index = -1 }
0054 #define _Py_static_string(varname, value)  static _Py_Identifier varname = _Py_static_string_init(value)
0055 #define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)
0056 
0057 #endif /* !Py_BUILD_CORE */
0058 
0059 
0060 typedef struct {
0061     /* Number implementations must check *both*
0062        arguments for proper type and implement the necessary conversions
0063        in the slot functions themselves. */
0064 
0065     binaryfunc nb_add;
0066     binaryfunc nb_subtract;
0067     binaryfunc nb_multiply;
0068     binaryfunc nb_remainder;
0069     binaryfunc nb_divmod;
0070     ternaryfunc nb_power;
0071     unaryfunc nb_negative;
0072     unaryfunc nb_positive;
0073     unaryfunc nb_absolute;
0074     inquiry nb_bool;
0075     unaryfunc nb_invert;
0076     binaryfunc nb_lshift;
0077     binaryfunc nb_rshift;
0078     binaryfunc nb_and;
0079     binaryfunc nb_xor;
0080     binaryfunc nb_or;
0081     unaryfunc nb_int;
0082     void *nb_reserved;  /* the slot formerly known as nb_long */
0083     unaryfunc nb_float;
0084 
0085     binaryfunc nb_inplace_add;
0086     binaryfunc nb_inplace_subtract;
0087     binaryfunc nb_inplace_multiply;
0088     binaryfunc nb_inplace_remainder;
0089     ternaryfunc nb_inplace_power;
0090     binaryfunc nb_inplace_lshift;
0091     binaryfunc nb_inplace_rshift;
0092     binaryfunc nb_inplace_and;
0093     binaryfunc nb_inplace_xor;
0094     binaryfunc nb_inplace_or;
0095 
0096     binaryfunc nb_floor_divide;
0097     binaryfunc nb_true_divide;
0098     binaryfunc nb_inplace_floor_divide;
0099     binaryfunc nb_inplace_true_divide;
0100 
0101     unaryfunc nb_index;
0102 
0103     binaryfunc nb_matrix_multiply;
0104     binaryfunc nb_inplace_matrix_multiply;
0105 } PyNumberMethods;
0106 
0107 typedef struct {
0108     lenfunc sq_length;
0109     binaryfunc sq_concat;
0110     ssizeargfunc sq_repeat;
0111     ssizeargfunc sq_item;
0112     void *was_sq_slice;
0113     ssizeobjargproc sq_ass_item;
0114     void *was_sq_ass_slice;
0115     objobjproc sq_contains;
0116 
0117     binaryfunc sq_inplace_concat;
0118     ssizeargfunc sq_inplace_repeat;
0119 } PySequenceMethods;
0120 
0121 typedef struct {
0122     lenfunc mp_length;
0123     binaryfunc mp_subscript;
0124     objobjargproc mp_ass_subscript;
0125 } PyMappingMethods;
0126 
0127 typedef PySendResult (*sendfunc)(PyObject *iter, PyObject *value, PyObject **result);
0128 
0129 typedef struct {
0130     unaryfunc am_await;
0131     unaryfunc am_aiter;
0132     unaryfunc am_anext;
0133     sendfunc am_send;
0134 } PyAsyncMethods;
0135 
0136 typedef struct {
0137      getbufferproc bf_getbuffer;
0138      releasebufferproc bf_releasebuffer;
0139 } PyBufferProcs;
0140 
0141 /* Allow printfunc in the tp_vectorcall_offset slot for
0142  * backwards-compatibility */
0143 typedef Py_ssize_t printfunc;
0144 
0145 // If this structure is modified, Doc/includes/typestruct.h should be updated
0146 // as well.
0147 struct _typeobject {
0148     PyObject_VAR_HEAD
0149     const char *tp_name; /* For printing, in format "<module>.<name>" */
0150     Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
0151 
0152     /* Methods to implement standard operations */
0153 
0154     destructor tp_dealloc;
0155     Py_ssize_t tp_vectorcall_offset;
0156     getattrfunc tp_getattr;
0157     setattrfunc tp_setattr;
0158     PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
0159                                     or tp_reserved (Python 3) */
0160     reprfunc tp_repr;
0161 
0162     /* Method suites for standard classes */
0163 
0164     PyNumberMethods *tp_as_number;
0165     PySequenceMethods *tp_as_sequence;
0166     PyMappingMethods *tp_as_mapping;
0167 
0168     /* More standard operations (here for binary compatibility) */
0169 
0170     hashfunc tp_hash;
0171     ternaryfunc tp_call;
0172     reprfunc tp_str;
0173     getattrofunc tp_getattro;
0174     setattrofunc tp_setattro;
0175 
0176     /* Functions to access object as input/output buffer */
0177     PyBufferProcs *tp_as_buffer;
0178 
0179     /* Flags to define presence of optional/expanded features */
0180     unsigned long tp_flags;
0181 
0182     const char *tp_doc; /* Documentation string */
0183 
0184     /* Assigned meaning in release 2.0 */
0185     /* call function for all accessible objects */
0186     traverseproc tp_traverse;
0187 
0188     /* delete references to contained objects */
0189     inquiry tp_clear;
0190 
0191     /* Assigned meaning in release 2.1 */
0192     /* rich comparisons */
0193     richcmpfunc tp_richcompare;
0194 
0195     /* weak reference enabler */
0196     Py_ssize_t tp_weaklistoffset;
0197 
0198     /* Iterators */
0199     getiterfunc tp_iter;
0200     iternextfunc tp_iternext;
0201 
0202     /* Attribute descriptor and subclassing stuff */
0203     PyMethodDef *tp_methods;
0204     PyMemberDef *tp_members;
0205     PyGetSetDef *tp_getset;
0206     // Strong reference on a heap type, borrowed reference on a static type
0207     PyTypeObject *tp_base;
0208     PyObject *tp_dict;
0209     descrgetfunc tp_descr_get;
0210     descrsetfunc tp_descr_set;
0211     Py_ssize_t tp_dictoffset;
0212     initproc tp_init;
0213     allocfunc tp_alloc;
0214     newfunc tp_new;
0215     freefunc tp_free; /* Low-level free-memory routine */
0216     inquiry tp_is_gc; /* For PyObject_IS_GC */
0217     PyObject *tp_bases;
0218     PyObject *tp_mro; /* method resolution order */
0219     PyObject *tp_cache; /* no longer used */
0220     void *tp_subclasses;  /* for static builtin types this is an index */
0221     PyObject *tp_weaklist; /* not used for static builtin types */
0222     destructor tp_del;
0223 
0224     /* Type attribute cache version tag. Added in version 2.6 */
0225     unsigned int tp_version_tag;
0226 
0227     destructor tp_finalize;
0228     vectorcallfunc tp_vectorcall;
0229 
0230     /* bitset of which type-watchers care about this type */
0231     unsigned char tp_watched;
0232     uint16_t tp_versions_used;
0233 };
0234 
0235 /* This struct is used by the specializer
0236  * It should be treated as an opaque blob
0237  * by code other than the specializer and interpreter. */
0238 struct _specialization_cache {
0239     // In order to avoid bloating the bytecode with lots of inline caches, the
0240     // members of this structure have a somewhat unique contract. They are set
0241     // by the specialization machinery, and are invalidated by PyType_Modified.
0242     // The rules for using them are as follows:
0243     // - If getitem is non-NULL, then it is the same Python function that
0244     //   PyType_Lookup(cls, "__getitem__") would return.
0245     // - If getitem is NULL, then getitem_version is meaningless.
0246     // - If getitem->func_version == getitem_version, then getitem can be called
0247     //   with two positional arguments and no keyword arguments, and has neither
0248     //   *args nor **kwargs (as required by BINARY_SUBSCR_GETITEM):
0249     PyObject *getitem;
0250     uint32_t getitem_version;
0251     PyObject *init;
0252 };
0253 
0254 /* The *real* layout of a type object when allocated on the heap */
0255 typedef struct _heaptypeobject {
0256     /* Note: there's a dependency on the order of these members
0257        in slotptr() in typeobject.c . */
0258     PyTypeObject ht_type;
0259     PyAsyncMethods as_async;
0260     PyNumberMethods as_number;
0261     PyMappingMethods as_mapping;
0262     PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
0263                                       so that the mapping wins when both
0264                                       the mapping and the sequence define
0265                                       a given operator (e.g. __getitem__).
0266                                       see add_operators() in typeobject.c . */
0267     PyBufferProcs as_buffer;
0268     PyObject *ht_name, *ht_slots, *ht_qualname;
0269     struct _dictkeysobject *ht_cached_keys;
0270     PyObject *ht_module;
0271     char *_ht_tpname;  // Storage for "tp_name"; see PyType_FromModuleAndSpec
0272     struct _specialization_cache _spec_cache; // For use by the specializer.
0273     /* here are optional user slots, followed by the members. */
0274 } PyHeapTypeObject;
0275 
0276 PyAPI_FUNC(const char *) _PyType_Name(PyTypeObject *);
0277 PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
0278 PyAPI_FUNC(PyObject *) _PyType_LookupRef(PyTypeObject *, PyObject *);
0279 PyAPI_FUNC(PyObject *) PyType_GetDict(PyTypeObject *);
0280 
0281 PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
0282 PyAPI_FUNC(void) _Py_BreakPoint(void);
0283 PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
0284 
0285 PyAPI_FUNC(PyObject*) _PyObject_GetAttrId(PyObject *, _Py_Identifier *);
0286 
0287 PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
0288 PyAPI_FUNC(void) PyObject_CallFinalizer(PyObject *);
0289 PyAPI_FUNC(int) PyObject_CallFinalizerFromDealloc(PyObject *);
0290 
0291 PyAPI_FUNC(void) PyUnstable_Object_ClearWeakRefsNoCallbacks(PyObject *);
0292 
0293 /* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes
0294    dict as the last parameter. */
0295 PyAPI_FUNC(PyObject *)
0296 _PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *, int);
0297 PyAPI_FUNC(int)
0298 _PyObject_GenericSetAttrWithDict(PyObject *, PyObject *,
0299                                  PyObject *, PyObject *);
0300 
0301 PyAPI_FUNC(PyObject *) _PyObject_FunctionStr(PyObject *);
0302 
0303 /* Safely decref `dst` and set `dst` to `src`.
0304  *
0305  * As in case of Py_CLEAR "the obvious" code can be deadly:
0306  *
0307  *     Py_DECREF(dst);
0308  *     dst = src;
0309  *
0310  * The safe way is:
0311  *
0312  *      Py_SETREF(dst, src);
0313  *
0314  * That arranges to set `dst` to `src` _before_ decref'ing, so that any code
0315  * triggered as a side-effect of `dst` getting torn down no longer believes
0316  * `dst` points to a valid object.
0317  *
0318  * Temporary variables are used to only evalutate macro arguments once and so
0319  * avoid the duplication of side effects. _Py_TYPEOF() or memcpy() is used to
0320  * avoid a miscompilation caused by type punning. See Py_CLEAR() comment for
0321  * implementation details about type punning.
0322  *
0323  * The memcpy() implementation does not emit a compiler warning if 'src' has
0324  * not the same type than 'src': any pointer type is accepted for 'src'.
0325  */
0326 #ifdef _Py_TYPEOF
0327 #define Py_SETREF(dst, src) \
0328     do { \
0329         _Py_TYPEOF(dst)* _tmp_dst_ptr = &(dst); \
0330         _Py_TYPEOF(dst) _tmp_old_dst = (*_tmp_dst_ptr); \
0331         *_tmp_dst_ptr = (src); \
0332         Py_DECREF(_tmp_old_dst); \
0333     } while (0)
0334 #else
0335 #define Py_SETREF(dst, src) \
0336     do { \
0337         PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \
0338         PyObject *_tmp_old_dst = (*_tmp_dst_ptr); \
0339         PyObject *_tmp_src = _PyObject_CAST(src); \
0340         memcpy(_tmp_dst_ptr, &_tmp_src, sizeof(PyObject*)); \
0341         Py_DECREF(_tmp_old_dst); \
0342     } while (0)
0343 #endif
0344 
0345 /* Py_XSETREF() is a variant of Py_SETREF() that uses Py_XDECREF() instead of
0346  * Py_DECREF().
0347  */
0348 #ifdef _Py_TYPEOF
0349 #define Py_XSETREF(dst, src) \
0350     do { \
0351         _Py_TYPEOF(dst)* _tmp_dst_ptr = &(dst); \
0352         _Py_TYPEOF(dst) _tmp_old_dst = (*_tmp_dst_ptr); \
0353         *_tmp_dst_ptr = (src); \
0354         Py_XDECREF(_tmp_old_dst); \
0355     } while (0)
0356 #else
0357 #define Py_XSETREF(dst, src) \
0358     do { \
0359         PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \
0360         PyObject *_tmp_old_dst = (*_tmp_dst_ptr); \
0361         PyObject *_tmp_src = _PyObject_CAST(src); \
0362         memcpy(_tmp_dst_ptr, &_tmp_src, sizeof(PyObject*)); \
0363         Py_XDECREF(_tmp_old_dst); \
0364     } while (0)
0365 #endif
0366 
0367 
0368 /* Define a pair of assertion macros:
0369    _PyObject_ASSERT_FROM(), _PyObject_ASSERT_WITH_MSG() and _PyObject_ASSERT().
0370 
0371    These work like the regular C assert(), in that they will abort the
0372    process with a message on stderr if the given condition fails to hold,
0373    but compile away to nothing if NDEBUG is defined.
0374 
0375    However, before aborting, Python will also try to call _PyObject_Dump() on
0376    the given object.  This may be of use when investigating bugs in which a
0377    particular object is corrupt (e.g. buggy a tp_visit method in an extension
0378    module breaking the garbage collector), to help locate the broken objects.
0379 
0380    The WITH_MSG variant allows you to supply an additional message that Python
0381    will attempt to print to stderr, after the object dump. */
0382 #ifdef NDEBUG
0383    /* No debugging: compile away the assertions: */
0384 #  define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \
0385     ((void)0)
0386 #else
0387    /* With debugging: generate checks: */
0388 #  define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \
0389     ((expr) \
0390       ? (void)(0) \
0391       : _PyObject_AssertFailed((obj), Py_STRINGIFY(expr), \
0392                                (msg), (filename), (lineno), (func)))
0393 #endif
0394 
0395 #define _PyObject_ASSERT_WITH_MSG(obj, expr, msg) \
0396     _PyObject_ASSERT_FROM((obj), expr, (msg), __FILE__, __LINE__, __func__)
0397 #define _PyObject_ASSERT(obj, expr) \
0398     _PyObject_ASSERT_WITH_MSG((obj), expr, NULL)
0399 
0400 #define _PyObject_ASSERT_FAILED_MSG(obj, msg) \
0401     _PyObject_AssertFailed((obj), NULL, (msg), __FILE__, __LINE__, __func__)
0402 
0403 /* Declare and define _PyObject_AssertFailed() even when NDEBUG is defined,
0404    to avoid causing compiler/linker errors when building extensions without
0405    NDEBUG against a Python built with NDEBUG defined.
0406 
0407    msg, expr and function can be NULL. */
0408 PyAPI_FUNC(void) _Py_NO_RETURN _PyObject_AssertFailed(
0409     PyObject *obj,
0410     const char *expr,
0411     const char *msg,
0412     const char *file,
0413     int line,
0414     const char *function);
0415 
0416 
0417 /* Trashcan mechanism, thanks to Christian Tismer.
0418 
0419 When deallocating a container object, it's possible to trigger an unbounded
0420 chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
0421 next" object in the chain to 0.  This can easily lead to stack overflows,
0422 especially in threads (which typically have less stack space to work with).
0423 
0424 A container object can avoid this by bracketing the body of its tp_dealloc
0425 function with a pair of macros:
0426 
0427 static void
0428 mytype_dealloc(mytype *p)
0429 {
0430     ... declarations go here ...
0431 
0432     PyObject_GC_UnTrack(p);        // must untrack first
0433     Py_TRASHCAN_BEGIN(p, mytype_dealloc)
0434     ... The body of the deallocator goes here, including all calls ...
0435     ... to Py_DECREF on contained objects.                         ...
0436     Py_TRASHCAN_END                // there should be no code after this
0437 }
0438 
0439 CAUTION:  Never return from the middle of the body!  If the body needs to
0440 "get out early", put a label immediately before the Py_TRASHCAN_END
0441 call, and goto it.  Else the call-depth counter (see below) will stay
0442 above 0 forever, and the trashcan will never get emptied.
0443 
0444 How it works:  The BEGIN macro increments a call-depth counter.  So long
0445 as this counter is small, the body of the deallocator is run directly without
0446 further ado.  But if the counter gets large, it instead adds p to a list of
0447 objects to be deallocated later, skips the body of the deallocator, and
0448 resumes execution after the END macro.  The tp_dealloc routine then returns
0449 without deallocating anything (and so unbounded call-stack depth is avoided).
0450 
0451 When the call stack finishes unwinding again, code generated by the END macro
0452 notices this, and calls another routine to deallocate all the objects that
0453 may have been added to the list of deferred deallocations.  In effect, a
0454 chain of N deallocations is broken into (N-1)/(Py_TRASHCAN_HEADROOM-1) pieces,
0455 with the call stack never exceeding a depth of Py_TRASHCAN_HEADROOM.
0456 
0457 Since the tp_dealloc of a subclass typically calls the tp_dealloc of the base
0458 class, we need to ensure that the trashcan is only triggered on the tp_dealloc
0459 of the actual class being deallocated. Otherwise we might end up with a
0460 partially-deallocated object. To check this, the tp_dealloc function must be
0461 passed as second argument to Py_TRASHCAN_BEGIN().
0462 */
0463 
0464 /* Python 3.9 private API, invoked by the macros below. */
0465 PyAPI_FUNC(int) _PyTrash_begin(PyThreadState *tstate, PyObject *op);
0466 PyAPI_FUNC(void) _PyTrash_end(PyThreadState *tstate);
0467 
0468 PyAPI_FUNC(void) _PyTrash_thread_deposit_object(PyThreadState *tstate, PyObject *op);
0469 PyAPI_FUNC(void) _PyTrash_thread_destroy_chain(PyThreadState *tstate);
0470 
0471 
0472 /* Python 3.10 private API, invoked by the Py_TRASHCAN_BEGIN(). */
0473 
0474 /* To avoid raising recursion errors during dealloc trigger trashcan before we reach
0475  * recursion limit. To avoid trashing, we don't attempt to empty the trashcan until
0476  * we have headroom above the trigger limit */
0477 #define Py_TRASHCAN_HEADROOM 50
0478 
0479 #define Py_TRASHCAN_BEGIN(op, dealloc) \
0480 do { \
0481     PyThreadState *tstate = PyThreadState_Get(); \
0482     if (tstate->c_recursion_remaining <= Py_TRASHCAN_HEADROOM && Py_TYPE(op)->tp_dealloc == (destructor)dealloc) { \
0483         _PyTrash_thread_deposit_object(tstate, (PyObject *)op); \
0484         break; \
0485     } \
0486     tstate->c_recursion_remaining--;
0487     /* The body of the deallocator is here. */
0488 #define Py_TRASHCAN_END \
0489     tstate->c_recursion_remaining++; \
0490     if (tstate->delete_later && tstate->c_recursion_remaining > (Py_TRASHCAN_HEADROOM*2)) { \
0491         _PyTrash_thread_destroy_chain(tstate); \
0492     } \
0493 } while (0);
0494 
0495 
0496 PyAPI_FUNC(void *) PyObject_GetItemData(PyObject *obj);
0497 
0498 PyAPI_FUNC(int) PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg);
0499 PyAPI_FUNC(int) _PyObject_SetManagedDict(PyObject *obj, PyObject *new_dict);
0500 PyAPI_FUNC(void) PyObject_ClearManagedDict(PyObject *obj);
0501 
0502 #define TYPE_MAX_WATCHERS 8
0503 
0504 typedef int(*PyType_WatchCallback)(PyTypeObject *);
0505 PyAPI_FUNC(int) PyType_AddWatcher(PyType_WatchCallback callback);
0506 PyAPI_FUNC(int) PyType_ClearWatcher(int watcher_id);
0507 PyAPI_FUNC(int) PyType_Watch(int watcher_id, PyObject *type);
0508 PyAPI_FUNC(int) PyType_Unwatch(int watcher_id, PyObject *type);
0509 
0510 /* Attempt to assign a version tag to the given type.
0511  *
0512  * Returns 1 if the type already had a valid version tag or a new one was
0513  * assigned, or 0 if a new tag could not be assigned.
0514  */
0515 PyAPI_FUNC(int) PyUnstable_Type_AssignVersionTag(PyTypeObject *type);
0516 
0517 
0518 typedef enum {
0519     PyRefTracer_CREATE = 0,
0520     PyRefTracer_DESTROY = 1,
0521 } PyRefTracerEvent;
0522 
0523 typedef int (*PyRefTracer)(PyObject *, PyRefTracerEvent event, void *);
0524 PyAPI_FUNC(int) PyRefTracer_SetTracer(PyRefTracer tracer, void *data);
0525 PyAPI_FUNC(PyRefTracer) PyRefTracer_GetTracer(void**);