1 #ifndef Py_OBJECT_H
2 #define Py_OBJECT_H
3 #ifdef __cplusplus
4 extern "C" {
5 #endif
6
7
8 /* Object and type object interface */
9
10 /*
11 Objects are structures allocated on the heap. Special rules apply to
12 the use of objects to ensure they are properly garbage-collected.
13 Objects are never allocated statically or on the stack; they must be
14 accessed through special macros and functions only. (Type objects are
15 exceptions to the first rule; the standard types are represented by
16 statically initialized type objects, although work on type/class unification
17 for Python 2.2 made it possible to have heap-allocated type objects too).
18
19 An object has a 'reference count' that is increased or decreased when a
20 pointer to the object is copied or deleted; when the reference count
21 reaches zero there are no references to the object left and it can be
22 removed from the heap.
23
24 An object has a 'type' that determines what it represents and what kind
25 of data it contains. An object's type is fixed when it is created.
26 Types themselves are represented as objects; an object contains a
27 pointer to the corresponding type object. The type itself has a type
28 pointer pointing to the object representing the type 'type', which
29 contains a pointer to itself!.
30
31 Objects do not float around in memory; once allocated an object keeps
32 the same size and address. Objects that must hold variable-size data
33 can contain pointers to variable-size parts of the object. Not all
34 objects of the same type have the same size; but the size cannot change
35 after allocation. (These restrictions are made so a reference to an
36 object can be simply a pointer -- moving an object would require
37 updating all the pointers, and changing an object's size would require
38 moving it if there was another object right next to it.)
39
40 Objects are always accessed through pointers of the type 'PyObject *'.
41 The type 'PyObject' is a structure that only contains the reference count
42 and the type pointer. The actual memory allocated for an object
43 contains other data that can only be accessed after casting the pointer
44 to a pointer to a longer structure type. This longer type must start
45 with the reference count and type fields; the macro PyObject_HEAD should be
46 used for this (to accommodate for future changes). The implementation
47 of a particular object type can cast the object pointer to the proper
48 type and back.
49
50 A standard interface exists for objects that contain an array of items
51 whose size is determined when the object is allocated.
52 */
53
54 #include "pystats.h"
55
56 /* Py_DEBUG implies Py_REF_DEBUG. */
57 #if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)
58 # define Py_REF_DEBUG
59 #endif
60
61 #if defined(Py_LIMITED_API) && defined(Py_TRACE_REFS)
62 # error Py_LIMITED_API is incompatible with Py_TRACE_REFS
63 #endif
64
65 #ifdef Py_TRACE_REFS
66 /* Define pointers to support a doubly-linked list of all live heap objects. */
67 #define _PyObject_HEAD_EXTRA \
68 PyObject *_ob_next; \
69 PyObject *_ob_prev;
70
71 #define _PyObject_EXTRA_INIT _Py_NULL, _Py_NULL,
72
73 #else
74 # define _PyObject_HEAD_EXTRA
75 # define _PyObject_EXTRA_INIT
76 #endif
77
78 /* PyObject_HEAD defines the initial segment of every PyObject. */
79 #define PyObject_HEAD PyObject ob_base;
80
81 /*
82 Immortalization:
83
84 The following indicates the immortalization strategy depending on the amount
85 of available bits in the reference count field. All strategies are backwards
86 compatible but the specific reference count value or immortalization check
87 might change depending on the specializations for the underlying system.
88
89 Proper deallocation of immortal instances requires distinguishing between
90 statically allocated immortal instances vs those promoted by the runtime to be
91 immortal. The latter should be the only instances that require
92 cleanup during runtime finalization.
93 */
94
95 #if SIZEOF_VOID_P > 4
96 /*
97 In 64+ bit systems, an object will be marked as immortal by setting all of the
98 lower 32 bits of the reference count field, which is equal to: 0xFFFFFFFF
99
100 Using the lower 32 bits makes the value backwards compatible by allowing
101 C-Extensions without the updated checks in Py_INCREF and Py_DECREF to safely
102 increase and decrease the objects reference count. The object would lose its
103 immortality, but the execution would still be correct.
104
105 Reference count increases will use saturated arithmetic, taking advantage of
106 having all the lower 32 bits set, which will avoid the reference count to go
107 beyond the refcount limit. Immortality checks for reference count decreases will
108 be done by checking the bit sign flag in the lower 32 bits.
109 */
110 #define _Py_IMMORTAL_REFCNT UINT_MAX
111
112 #else
113 /*
114 In 32 bit systems, an object will be marked as immortal by setting all of the
115 lower 30 bits of the reference count field, which is equal to: 0x3FFFFFFF
116
117 Using the lower 30 bits makes the value backwards compatible by allowing
118 C-Extensions without the updated checks in Py_INCREF and Py_DECREF to safely
119 increase and decrease the objects reference count. The object would lose its
120 immortality, but the execution would still be correct.
121
122 Reference count increases and decreases will first go through an immortality
123 check by comparing the reference count field to the immortality reference count.
124 */
125 #define _Py_IMMORTAL_REFCNT (UINT_MAX >> 2)
126 #endif
127
128 // Make all internal uses of PyObject_HEAD_INIT immortal while preserving the
129 // C-API expectation that the refcnt will be set to 1.
130 #ifdef Py_BUILD_CORE
131 #define PyObject_HEAD_INIT(type) \
132 { \
133 _PyObject_EXTRA_INIT \
134 { _Py_IMMORTAL_REFCNT }, \
135 (type) \
136 },
137 #else
138 #define PyObject_HEAD_INIT(type) \
139 { \
140 _PyObject_EXTRA_INIT \
141 { 1 }, \
142 (type) \
143 },
144 #endif /* Py_BUILD_CORE */
145
146 #define PyVarObject_HEAD_INIT(type, size) \
147 { \
148 PyObject_HEAD_INIT(type) \
149 (size) \
150 },
151
152 /* PyObject_VAR_HEAD defines the initial segment of all variable-size
153 * container objects. These end with a declaration of an array with 1
154 * element, but enough space is malloc'ed so that the array actually
155 * has room for ob_size elements. Note that ob_size is an element count,
156 * not necessarily a byte count.
157 */
158 #define PyObject_VAR_HEAD PyVarObject ob_base;
159 #define Py_INVALID_SIZE (Py_ssize_t)-1
160
161 /* Nothing is actually declared to be a PyObject, but every pointer to
162 * a Python object can be cast to a PyObject*. This is inheritance built
163 * by hand. Similarly every pointer to a variable-size Python object can,
164 * in addition, be cast to PyVarObject*.
165 */
166 struct _object {
167 _PyObject_HEAD_EXTRA
168
169 #if (defined(__GNUC__) || defined(__clang__)) \
170 && !(defined __STDC_VERSION__ && __STDC_VERSION__ >= 201112L)
171 // On C99 and older, anonymous union is a GCC and clang extension
172 __extension__
173 #endif
174 #ifdef _MSC_VER
175 // Ignore MSC warning C4201: "nonstandard extension used:
176 // nameless struct/union"
177 __pragma(warning(push))
178 __pragma(warning(disable: 4201))
179 #endif
180 union {
181 Py_ssize_t ob_refcnt;
182 #if SIZEOF_VOID_P > 4
183 PY_UINT32_T ob_refcnt_split[2];
184 #endif
185 };
186 #ifdef _MSC_VER
187 __pragma(warning(pop))
188 #endif
189
190 PyTypeObject *ob_type;
191 };
192
193 /* Cast argument to PyObject* type. */
194 #define _PyObject_CAST(op) _Py_CAST(PyObject*, (op))
195
196 typedef struct {
197 PyObject ob_base;
198 Py_ssize_t ob_size; /* Number of items in variable part */
199 } PyVarObject;
200
201 /* Cast argument to PyVarObject* type. */
202 #define _PyVarObject_CAST(op) _Py_CAST(PyVarObject*, (op))
203
204
205 // Test if the 'x' object is the 'y' object, the same as "x is y" in Python.
206 PyAPI_FUNC(int) Py_Is(PyObject *x, PyObject *y);
207 #define Py_Is(x, y) ((x) == (y))
208
209
210 static inline Py_ssize_t Py_REFCNT(PyObject *ob) {
211 return ob->ob_refcnt;
212 }
213 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
214 # define Py_REFCNT(ob) Py_REFCNT(_PyObject_CAST(ob))
215 #endif
216
217
218 // bpo-39573: The Py_SET_TYPE() function must be used to set an object type.
219 static inline PyTypeObject* Py_TYPE(PyObject *ob) {
220 return ob->ob_type;
221 }
222 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
223 # define Py_TYPE(ob) Py_TYPE(_PyObject_CAST(ob))
224 #endif
225
226 PyAPI_DATA(PyTypeObject) PyLong_Type;
227 PyAPI_DATA(PyTypeObject) PyBool_Type;
228
229 // bpo-39573: The Py_SET_SIZE() function must be used to set an object size.
230 static inline Py_ssize_t Py_SIZE(PyObject *ob) {
231 assert(ob->ob_type != &PyLong_Type);
232 assert(ob->ob_type != &PyBool_Type);
233 PyVarObject *var_ob = _PyVarObject_CAST(ob);
234 return var_ob->ob_size;
235 }
236 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
237 # define Py_SIZE(ob) Py_SIZE(_PyObject_CAST(ob))
238 #endif
239
240 static inline Py_ALWAYS_INLINE int _Py_IsImmortal(PyObject *op)
241 {
242 #if SIZEOF_VOID_P > 4
243 return _Py_CAST(PY_INT32_T, op->ob_refcnt) < 0;
244 #else
245 return op->ob_refcnt == _Py_IMMORTAL_REFCNT;
246 #endif
247 }
248 #define _Py_IsImmortal(op) _Py_IsImmortal(_PyObject_CAST(op))
249
250 static inline int Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {
251 return Py_TYPE(ob) == type;
252 }
253 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
254 # define Py_IS_TYPE(ob, type) Py_IS_TYPE(_PyObject_CAST(ob), (type))
255 #endif
256
257
258 static inline void Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt) {
259 // This immortal check is for code that is unaware of immortal objects.
260 // The runtime tracks these objects and we should avoid as much
261 // as possible having extensions inadvertently change the refcnt
262 // of an immortalized object.
263 if (_Py_IsImmortal(ob)) {
264 return;
265 }
266 ob->ob_refcnt = refcnt;
267 }
268 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
269 # define Py_SET_REFCNT(ob, refcnt) Py_SET_REFCNT(_PyObject_CAST(ob), (refcnt))
270 #endif
271
272
273 static inline void Py_SET_TYPE(PyObject *ob, PyTypeObject *type) {
274 ob->ob_type = type;
275 }
276 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
277 # define Py_SET_TYPE(ob, type) Py_SET_TYPE(_PyObject_CAST(ob), type)
278 #endif
279
280 static inline void Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size) {
281 assert(ob->ob_base.ob_type != &PyLong_Type);
282 assert(ob->ob_base.ob_type != &PyBool_Type);
283 ob->ob_size = size;
284 }
285 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
286 # define Py_SET_SIZE(ob, size) Py_SET_SIZE(_PyVarObject_CAST(ob), (size))
287 #endif
288
289
290 /*
291 Type objects contain a string containing the type name (to help somewhat
292 in debugging), the allocation parameters (see PyObject_New() and
293 PyObject_NewVar()),
294 and methods for accessing objects of the type. Methods are optional, a
295 nil pointer meaning that particular kind of access is not available for
296 this type. The Py_DECREF() macro uses the tp_dealloc method without
297 checking for a nil pointer; it should always be implemented except if
298 the implementation can guarantee that the reference count will never
299 reach zero (e.g., for statically allocated type objects).
300
301 NB: the methods for certain type groups are now contained in separate
302 method blocks.
303 */
304
305 typedef PyObject * (*unaryfunc)(PyObject *);
306 typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
307 typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
308 typedef int (*inquiry)(PyObject *);
309 typedef Py_ssize_t (*lenfunc)(PyObject *);
310 typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
311 typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
312 typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
313 typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
314 typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
315
316 typedef int (*objobjproc)(PyObject *, PyObject *);
317 typedef int (*visitproc)(PyObject *, void *);
318 typedef int (*traverseproc)(PyObject *, visitproc, void *);
319
320
321 typedef void (*freefunc)(void *);
322 typedef void (*destructor)(PyObject *);
323 typedef PyObject *(*getattrfunc)(PyObject *, char *);
324 typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
325 typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
326 typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
327 typedef PyObject *(*reprfunc)(PyObject *);
328 typedef Py_hash_t (*hashfunc)(PyObject *);
329 typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
330 typedef PyObject *(*getiterfunc) (PyObject *);
331 typedef PyObject *(*iternextfunc) (PyObject *);
332 typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
333 typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
334 typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
335 typedef PyObject *(*newfunc)(PyTypeObject *, PyObject *, PyObject *);
336 typedef PyObject *(*allocfunc)(PyTypeObject *, Py_ssize_t);
337
338 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030c0000 // 3.12
339 typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args,
340 size_t nargsf, PyObject *kwnames);
341 #endif
342
343 typedef struct{
344 int slot; /* slot id, see below */
345 void *pfunc; /* function pointer */
346 } PyType_Slot;
347
348 typedef struct{
349 const char* name;
350 int basicsize;
351 int itemsize;
352 unsigned int flags;
353 PyType_Slot *slots; /* terminated by slot==0. */
354 } PyType_Spec;
355
356 PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
357 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
358 PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);
359 #endif
360 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
361 PyAPI_FUNC(void*) PyType_GetSlot(PyTypeObject*, int);
362 #endif
363 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03090000
364 PyAPI_FUNC(PyObject*) PyType_FromModuleAndSpec(PyObject *, PyType_Spec *, PyObject *);
365 PyAPI_FUNC(PyObject *) PyType_GetModule(PyTypeObject *);
366 PyAPI_FUNC(void *) PyType_GetModuleState(PyTypeObject *);
367 #endif
368 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030B0000
369 PyAPI_FUNC(PyObject *) PyType_GetName(PyTypeObject *);
370 PyAPI_FUNC(PyObject *) PyType_GetQualName(PyTypeObject *);
371 #endif
372 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030C0000
373 PyAPI_FUNC(PyObject *) PyType_FromMetaclass(PyTypeObject*, PyObject*, PyType_Spec*, PyObject*);
374 PyAPI_FUNC(void *) PyObject_GetTypeData(PyObject *obj, PyTypeObject *cls);
375 PyAPI_FUNC(Py_ssize_t) PyType_GetTypeDataSize(PyTypeObject *cls);
376 #endif
377
378 /* Generic type check */
379 PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
380
381 static inline int PyObject_TypeCheck(PyObject *ob, PyTypeObject *type) {
382 return Py_IS_TYPE(ob, type) || PyType_IsSubtype(Py_TYPE(ob), type);
383 }
384 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
385 # define PyObject_TypeCheck(ob, type) PyObject_TypeCheck(_PyObject_CAST(ob), (type))
386 #endif
387
388 PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
389 PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
390 PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
391
392 PyAPI_FUNC(unsigned long) PyType_GetFlags(PyTypeObject*);
393
394 PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
395 PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
396 PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
397 PyObject *, PyObject *);
398 PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
399 PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
400
401 /* Generic operations on objects */
402 PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
403 PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
404 PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
405 PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
406 PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
407 PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
408 PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
409 PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
410 PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
411 PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
412 PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
413 PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
414 PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
415 PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
416 PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *);
417 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
418 PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
419 #endif
420 PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
421 PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
422 PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
423 PyAPI_FUNC(int) PyObject_Not(PyObject *);
424 PyAPI_FUNC(int) PyCallable_Check(PyObject *);
425 PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
426
427 /* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
428 list of strings. PyObject_Dir(NULL) is like builtins.dir(),
429 returning the names of the current locals. In this case, if there are
430 no current locals, NULL is returned, and PyErr_Occurred() is false.
431 */
432 PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
433
434 /* Pickle support. */
435 #ifndef Py_LIMITED_API
436 PyAPI_FUNC(PyObject *) _PyObject_GetState(PyObject *);
437 #endif
438
439
440 /* Helpers for printing recursive container types */
441 PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
442 PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
443
444 /* Flag bits for printing: */
445 #define Py_PRINT_RAW 1 /* No string quotes etc. */
446
447 /*
448 Type flags (tp_flags)
449
450 These flags are used to change expected features and behavior for a
451 particular type.
452
453 Arbitration of the flag bit positions will need to be coordinated among
454 all extension writers who publicly release their extensions (this will
455 be fewer than you might expect!).
456
457 Most flags were removed as of Python 3.0 to make room for new flags. (Some
458 flags are not for backwards compatibility but to indicate the presence of an
459 optional feature; these flags remain of course.)
460
461 Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
462
463 Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
464 given type object has a specified feature.
465 */
466
467 #ifndef Py_LIMITED_API
468
469 /* Track types initialized using _PyStaticType_InitBuiltin(). */
470 #define _Py_TPFLAGS_STATIC_BUILTIN (1 << 1)
471
472 /* Placement of weakref pointers are managed by the VM, not by the type.
473 * The VM will automatically set tp_weaklistoffset.
474 */
475 #define Py_TPFLAGS_MANAGED_WEAKREF (1 << 3)
476
477 /* Placement of dict (and values) pointers are managed by the VM, not by the type.
478 * The VM will automatically set tp_dictoffset.
479 */
480 #define Py_TPFLAGS_MANAGED_DICT (1 << 4)
481
482 #define Py_TPFLAGS_PREHEADER (Py_TPFLAGS_MANAGED_WEAKREF | Py_TPFLAGS_MANAGED_DICT)
483
484 /* Set if instances of the type object are treated as sequences for pattern matching */
485 #define Py_TPFLAGS_SEQUENCE (1 << 5)
486 /* Set if instances of the type object are treated as mappings for pattern matching */
487 #define Py_TPFLAGS_MAPPING (1 << 6)
488 #endif
489
490 /* Disallow creating instances of the type: set tp_new to NULL and don't create
491 * the "__new__" key in the type dictionary. */
492 #define Py_TPFLAGS_DISALLOW_INSTANTIATION (1UL << 7)
493
494 /* Set if the type object is immutable: type attributes cannot be set nor deleted */
495 #define Py_TPFLAGS_IMMUTABLETYPE (1UL << 8)
496
497 /* Set if the type object is dynamically allocated */
498 #define Py_TPFLAGS_HEAPTYPE (1UL << 9)
499
500 /* Set if the type allows subclassing */
501 #define Py_TPFLAGS_BASETYPE (1UL << 10)
502
503 /* Set if the type implements the vectorcall protocol (PEP 590) */
504 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030C0000
505 #define Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)
506 #ifndef Py_LIMITED_API
507 // Backwards compatibility alias for API that was provisional in Python 3.8
508 #define _Py_TPFLAGS_HAVE_VECTORCALL Py_TPFLAGS_HAVE_VECTORCALL
509 #endif
510 #endif
511
512 /* Set if the type is 'ready' -- fully initialized */
513 #define Py_TPFLAGS_READY (1UL << 12)
514
515 /* Set while the type is being 'readied', to prevent recursive ready calls */
516 #define Py_TPFLAGS_READYING (1UL << 13)
517
518 /* Objects support garbage collection (see objimpl.h) */
519 #define Py_TPFLAGS_HAVE_GC (1UL << 14)
520
521 /* These two bits are preserved for Stackless Python, next after this is 17 */
522 #ifdef STACKLESS
523 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)
524 #else
525 #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
526 #endif
527
528 /* Objects behave like an unbound method */
529 #define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
530
531 /* Object has up-to-date type attribute cache */
532 #define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19)
533
534 /* Type is abstract and cannot be instantiated */
535 #define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)
536
537 // This undocumented flag gives certain built-ins their unique pattern-matching
538 // behavior, which allows a single positional subpattern to match against the
539 // subject itself (rather than a mapped attribute on it):
540 #define _Py_TPFLAGS_MATCH_SELF (1UL << 22)
541
542 /* Items (ob_size*tp_itemsize) are found at the end of an instance's memory */
543 #define Py_TPFLAGS_ITEMS_AT_END (1UL << 23)
544
545 /* These flags are used to determine if a type is a subclass. */
546 #define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24)
547 #define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25)
548 #define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26)
549 #define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27)
550 #define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28)
551 #define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29)
552 #define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30)
553 #define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31)
554
555 #define Py_TPFLAGS_DEFAULT ( \
556 Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
557 0)
558
559 /* NOTE: Some of the following flags reuse lower bits (removed as part of the
560 * Python 3.0 transition). */
561
562 /* The following flags are kept for compatibility; in previous
563 * versions they indicated presence of newer tp_* fields on the
564 * type struct.
565 * Starting with 3.8, binary compatibility of C extensions across
566 * feature releases of Python is not supported anymore (except when
567 * using the stable ABI, in which all classes are created dynamically,
568 * using the interpreter's memory layout.)
569 * Note that older extensions using the stable ABI set these flags,
570 * so the bits must not be repurposed.
571 */
572 #define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)
573 #define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18)
574
575
576 /*
577 The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
578 reference counts. Py_DECREF calls the object's deallocator function when
579 the refcount falls to 0; for
580 objects that don't contain references to other objects or heap memory
581 this can be the standard function free(). Both macros can be used
582 wherever a void expression is allowed. The argument must not be a
583 NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
584 The macro _Py_NewReference(op) initialize reference counts to 1, and
585 in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
586 bookkeeping appropriate to the special build.
587
588 We assume that the reference count field can never overflow; this can
589 be proven when the size of the field is the same as the pointer size, so
590 we ignore the possibility. Provided a C int is at least 32 bits (which
591 is implicitly assumed in many parts of this code), that's enough for
592 about 2**31 references to an object.
593
594 XXX The following became out of date in Python 2.2, but I'm not sure
595 XXX what the full truth is now. Certainly, heap-allocated type objects
596 XXX can and should be deallocated.
597 Type objects should never be deallocated; the type pointer in an object
598 is not considered to be a reference to the type object, to save
599 complications in the deallocation function. (This is actually a
600 decision that's up to the implementer of each new type so if you want,
601 you can count such references to the type object.)
602 */
603
604 #if defined(Py_REF_DEBUG) && !defined(Py_LIMITED_API)
605 PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
606 PyObject *op);
607 PyAPI_FUNC(void) _Py_INCREF_IncRefTotal(void);
608 PyAPI_FUNC(void) _Py_DECREF_DecRefTotal(void);
609 #endif // Py_REF_DEBUG && !Py_LIMITED_API
610
611 PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
612
613 /*
614 These are provided as conveniences to Python runtime embedders, so that
615 they can have object code that is not dependent on Python compilation flags.
616 */
617 PyAPI_FUNC(void) Py_IncRef(PyObject *);
618 PyAPI_FUNC(void) Py_DecRef(PyObject *);
619
620 // Similar to Py_IncRef() and Py_DecRef() but the argument must be non-NULL.
621 // Private functions used by Py_INCREF() and Py_DECREF().
622 PyAPI_FUNC(void) _Py_IncRef(PyObject *);
623 PyAPI_FUNC(void) _Py_DecRef(PyObject *);
624
625 static inline Py_ALWAYS_INLINE void Py_INCREF(PyObject *op)
626 {
627 #if defined(Py_LIMITED_API) && (Py_LIMITED_API+0 >= 0x030c0000 || defined(Py_REF_DEBUG))
628 // Stable ABI implements Py_INCREF() as a function call on limited C API
629 // version 3.12 and newer, and on Python built in debug mode. _Py_IncRef()
630 // was added to Python 3.10.0a7, use Py_IncRef() on older Python versions.
631 // Py_IncRef() accepts NULL whereas _Py_IncRef() doesn't.
632 # if Py_LIMITED_API+0 >= 0x030a00A7
633 _Py_IncRef(op);
634 # else
635 Py_IncRef(op);
636 # endif
637 #else
638 // Non-limited C API and limited C API for Python 3.9 and older access
639 // directly PyObject.ob_refcnt.
640 #if SIZEOF_VOID_P > 4
641 // Portable saturated add, branching on the carry flag and set low bits
642 PY_UINT32_T cur_refcnt = op->ob_refcnt_split[PY_BIG_ENDIAN];
643 PY_UINT32_T new_refcnt = cur_refcnt + 1;
644 if (new_refcnt == 0) {
645 return;
646 }
647 op->ob_refcnt_split[PY_BIG_ENDIAN] = new_refcnt;
648 #else
649 // Explicitly check immortality against the immortal value
650 if (_Py_IsImmortal(op)) {
651 return;
652 }
653 op->ob_refcnt++;
654 #endif
655 _Py_INCREF_STAT_INC();
656 #ifdef Py_REF_DEBUG
657 _Py_INCREF_IncRefTotal();
658 #endif
659 #endif
660 }
661 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
662 # define Py_INCREF(op) Py_INCREF(_PyObject_CAST(op))
663 #endif
664
665 #if defined(Py_LIMITED_API) && (Py_LIMITED_API+0 >= 0x030c0000 || defined(Py_REF_DEBUG))
666 // Stable ABI implements Py_DECREF() as a function call on limited C API
667 // version 3.12 and newer, and on Python built in debug mode. _Py_DecRef() was
668 // added to Python 3.10.0a7, use Py_DecRef() on older Python versions.
669 // Py_DecRef() accepts NULL whereas _Py_IncRef() doesn't.
670 static inline void Py_DECREF(PyObject *op) {
671 # if Py_LIMITED_API+0 >= 0x030a00A7
672 _Py_DecRef(op);
673 # else
674 Py_DecRef(op);
675 # endif
676 }
677 #define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
678
679 #elif defined(Py_REF_DEBUG)
680 static inline void Py_DECREF(const char *filename, int lineno, PyObject *op)
681 {
682 if (op->ob_refcnt <= 0) {
683 _Py_NegativeRefcount(filename, lineno, op);
684 }
685 if (_Py_IsImmortal(op)) {
686 return;
687 }
688 _Py_DECREF_STAT_INC();
689 _Py_DECREF_DecRefTotal();
690 if (--op->ob_refcnt == 0) {
691 _Py_Dealloc(op);
692 }
693 }
694 #define Py_DECREF(op) Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
695
696 #else
697 static inline Py_ALWAYS_INLINE void Py_DECREF(PyObject *op)
698 {
699 // Non-limited C API and limited C API for Python 3.9 and older access
700 // directly PyObject.ob_refcnt.
701 if (_Py_IsImmortal(op)) {
702 return;
703 }
704 _Py_DECREF_STAT_INC();
705 if (--op->ob_refcnt == 0) {
706 _Py_Dealloc(op);
707 }
708 }
709 #define Py_DECREF(op) Py_DECREF(_PyObject_CAST(op))
710 #endif
711
712
713 /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
714 * and tp_dealloc implementations.
715 *
716 * Note that "the obvious" code can be deadly:
717 *
718 * Py_XDECREF(op);
719 * op = NULL;
720 *
721 * Typically, `op` is something like self->containee, and `self` is done
722 * using its `containee` member. In the code sequence above, suppose
723 * `containee` is non-NULL with a refcount of 1. Its refcount falls to
724 * 0 on the first line, which can trigger an arbitrary amount of code,
725 * possibly including finalizers (like __del__ methods or weakref callbacks)
726 * coded in Python, which in turn can release the GIL and allow other threads
727 * to run, etc. Such code may even invoke methods of `self` again, or cause
728 * cyclic gc to trigger, but-- oops! --self->containee still points to the
729 * object being torn down, and it may be in an insane state while being torn
730 * down. This has in fact been a rich historic source of miserable (rare &
731 * hard-to-diagnose) segfaulting (and other) bugs.
732 *
733 * The safe way is:
734 *
735 * Py_CLEAR(op);
736 *
737 * That arranges to set `op` to NULL _before_ decref'ing, so that any code
738 * triggered as a side-effect of `op` getting torn down no longer believes
739 * `op` points to a valid object.
740 *
741 * There are cases where it's safe to use the naive code, but they're brittle.
742 * For example, if `op` points to a Python integer, you know that destroying
743 * one of those can't cause problems -- but in part that relies on that
744 * Python integers aren't currently weakly referencable. Best practice is
745 * to use Py_CLEAR() even if you can't think of a reason for why you need to.
746 *
747 * gh-98724: Use a temporary variable to only evaluate the macro argument once,
748 * to avoid the duplication of side effects if the argument has side effects.
749 *
750 * gh-99701: If the PyObject* type is used with casting arguments to PyObject*,
751 * the code can be miscompiled with strict aliasing because of type punning.
752 * With strict aliasing, a compiler considers that two pointers of different
753 * types cannot read or write the same memory which enables optimization
754 * opportunities.
755 *
756 * If available, use _Py_TYPEOF() to use the 'op' type for temporary variables,
757 * and so avoid type punning. Otherwise, use memcpy() which causes type erasure
758 * and so prevents the compiler to reuse an old cached 'op' value after
759 * Py_CLEAR().
760 */
761 #ifdef _Py_TYPEOF
762 #define Py_CLEAR(op) \
763 do { \
764 _Py_TYPEOF(op)* _tmp_op_ptr = &(op); \
765 _Py_TYPEOF(op) _tmp_old_op = (*_tmp_op_ptr); \
766 if (_tmp_old_op != NULL) { \
767 *_tmp_op_ptr = _Py_NULL; \
768 Py_DECREF(_tmp_old_op); \
769 } \
770 } while (0)
771 #else
772 #define Py_CLEAR(op) \
773 do { \
774 PyObject **_tmp_op_ptr = _Py_CAST(PyObject**, &(op)); \
775 PyObject *_tmp_old_op = (*_tmp_op_ptr); \
776 if (_tmp_old_op != NULL) { \
777 PyObject *_null_ptr = _Py_NULL; \
778 memcpy(_tmp_op_ptr, &_null_ptr, sizeof(PyObject*)); \
779 Py_DECREF(_tmp_old_op); \
780 } \
781 } while (0)
782 #endif
783
784
785 /* Function to use in case the object pointer can be NULL: */
786 static inline void Py_XINCREF(PyObject *op)
787 {
788 if (op != _Py_NULL) {
789 Py_INCREF(op);
790 }
791 }
792 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
793 # define Py_XINCREF(op) Py_XINCREF(_PyObject_CAST(op))
794 #endif
795
796 static inline void Py_XDECREF(PyObject *op)
797 {
798 if (op != _Py_NULL) {
799 Py_DECREF(op);
800 }
801 }
802 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
803 # define Py_XDECREF(op) Py_XDECREF(_PyObject_CAST(op))
804 #endif
805
806 // Create a new strong reference to an object:
807 // increment the reference count of the object and return the object.
808 PyAPI_FUNC(PyObject*) Py_NewRef(PyObject *obj);
809
810 // Similar to Py_NewRef(), but the object can be NULL.
811 PyAPI_FUNC(PyObject*) Py_XNewRef(PyObject *obj);
812
813 static inline PyObject* _Py_NewRef(PyObject *obj)
814 {
815 Py_INCREF(obj);
816 return obj;
817 }
818
819 static inline PyObject* _Py_XNewRef(PyObject *obj)
820 {
821 Py_XINCREF(obj);
822 return obj;
823 }
824
825 // Py_NewRef() and Py_XNewRef() are exported as functions for the stable ABI.
826 // Names overridden with macros by static inline functions for best
827 // performances.
828 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
829 # define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))
830 # define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))
831 #else
832 # define Py_NewRef(obj) _Py_NewRef(obj)
833 # define Py_XNewRef(obj) _Py_XNewRef(obj)
834 #endif
835
836
837 /*
838 _Py_NoneStruct is an object of undefined type which can be used in contexts
839 where NULL (nil) is not suitable (since NULL often means 'error').
840
841 Don't forget to apply Py_INCREF() when returning this value!!!
842 */
843 PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
844 #define Py_None (&_Py_NoneStruct)
845
846 // Test if an object is the None singleton, the same as "x is None" in Python.
847 PyAPI_FUNC(int) Py_IsNone(PyObject *x);
848 #define Py_IsNone(x) Py_Is((x), Py_None)
849
850 /* Macro for returning Py_None from a function */
851 #define Py_RETURN_NONE return Py_None
852
853 /*
854 Py_NotImplemented is a singleton used to signal that an operation is
855 not implemented for a given type combination.
856 */
857 PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
858 #define Py_NotImplemented (&_Py_NotImplementedStruct)
859
860 /* Macro for returning Py_NotImplemented from a function */
861 #define Py_RETURN_NOTIMPLEMENTED return Py_NotImplemented
862
863 /* Rich comparison opcodes */
864 #define Py_LT 0
865 #define Py_LE 1
866 #define Py_EQ 2
867 #define Py_NE 3
868 #define Py_GT 4
869 #define Py_GE 5
870
871 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000
872 /* Result of calling PyIter_Send */
873 typedef enum {
874 PYGEN_RETURN = 0,
875 PYGEN_ERROR = -1,
876 PYGEN_NEXT = 1,
877 } PySendResult;
878 #endif
879
880 /*
881 * Macro for implementing rich comparisons
882 *
883 * Needs to be a macro because any C-comparable type can be used.
884 */
885 #define Py_RETURN_RICHCOMPARE(val1, val2, op) \
886 do { \
887 switch (op) { \
888 case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
889 case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
890 case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
891 case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
892 case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
893 case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
894 default: \
895 Py_UNREACHABLE(); \
896 } \
897 } while (0)
898
899
900 /*
901 More conventions
902 ================
903
904 Argument Checking
905 -----------------
906
907 Functions that take objects as arguments normally don't check for nil
908 arguments, but they do check the type of the argument, and return an
909 error if the function doesn't apply to the type.
910
911 Failure Modes
912 -------------
913
914 Functions may fail for a variety of reasons, including running out of
915 memory. This is communicated to the caller in two ways: an error string
916 is set (see errors.h), and the function result differs: functions that
917 normally return a pointer return NULL for failure, functions returning
918 an integer return -1 (which could be a legal return value too!), and
919 other functions return 0 for success and -1 for failure.
920 Callers should always check for errors before using the result. If
921 an error was set, the caller must either explicitly clear it, or pass
922 the error on to its caller.
923
924 Reference Counts
925 ----------------
926
927 It takes a while to get used to the proper usage of reference counts.
928
929 Functions that create an object set the reference count to 1; such new
930 objects must be stored somewhere or destroyed again with Py_DECREF().
931 Some functions that 'store' objects, such as PyTuple_SetItem() and
932 PyList_SetItem(),
933 don't increment the reference count of the object, since the most
934 frequent use is to store a fresh object. Functions that 'retrieve'
935 objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
936 don't increment
937 the reference count, since most frequently the object is only looked at
938 quickly. Thus, to retrieve an object and store it again, the caller
939 must call Py_INCREF() explicitly.
940
941 NOTE: functions that 'consume' a reference count, like
942 PyList_SetItem(), consume the reference even if the object wasn't
943 successfully stored, to simplify error handling.
944
945 It seems attractive to make other functions that take an object as
946 argument consume a reference count; however, this may quickly get
947 confusing (even the current practice is already confusing). Consider
948 it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
949 times.
950 */
951
952 #ifndef Py_LIMITED_API
953 # define Py_CPYTHON_OBJECT_H
954 # include "cpython/object.h"
955 # undef Py_CPYTHON_OBJECT_H
956 #endif
957
958
959 static inline int
960 PyType_HasFeature(PyTypeObject *type, unsigned long feature)
961 {
962 unsigned long flags;
963 #ifdef Py_LIMITED_API
964 // PyTypeObject is opaque in the limited C API
965 flags = PyType_GetFlags(type);
966 #else
967 flags = type->tp_flags;
968 #endif
969 return ((flags & feature) != 0);
970 }
971
972 #define PyType_FastSubclass(type, flag) PyType_HasFeature((type), (flag))
973
974 static inline int PyType_Check(PyObject *op) {
975 return PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS);
976 }
977 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
978 # define PyType_Check(op) PyType_Check(_PyObject_CAST(op))
979 #endif
980
981 #define _PyType_CAST(op) \
982 (assert(PyType_Check(op)), _Py_CAST(PyTypeObject*, (op)))
983
984 static inline int PyType_CheckExact(PyObject *op) {
985 return Py_IS_TYPE(op, &PyType_Type);
986 }
987 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000
988 # define PyType_CheckExact(op) PyType_CheckExact(_PyObject_CAST(op))
989 #endif
990
991 #ifdef __cplusplus
992 }
993 #endif
994 #endif // !Py_OBJECT_H