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