object.h 36 KB

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