object.h 36 KB

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