object.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. #ifndef Py_OBJECT_H
  2. #define Py_OBJECT_H
  3. #include "pymem.h" /* _Py_tracemalloc_config */
  4. #ifdef __cplusplus
  5. extern "C" {
  6. #endif
  7. /* Object and type object interface */
  8. /*
  9. Objects are structures allocated on the heap. Special rules apply to
  10. the use of objects to ensure they are properly garbage-collected.
  11. Objects are never allocated statically or on the stack; they must be
  12. accessed through special macros and functions only. (Type objects are
  13. exceptions to the first rule; the standard types are represented by
  14. statically initialized type objects, although work on type/class unification
  15. for Python 2.2 made it possible to have heap-allocated type objects too).
  16. An object has a 'reference count' that is increased or decreased when a
  17. pointer to the object is copied or deleted; when the reference count
  18. reaches zero there are no references to the object left and it can be
  19. removed from the heap.
  20. An object has a 'type' that determines what it represents and what kind
  21. of data it contains. An object's type is fixed when it is created.
  22. Types themselves are represented as objects; an object contains a
  23. pointer to the corresponding type object. The type itself has a type
  24. pointer pointing to the object representing the type 'type', which
  25. contains a pointer to itself!).
  26. Objects do not float around in memory; once allocated an object keeps
  27. the same size and address. Objects that must hold variable-size data
  28. can contain pointers to variable-size parts of the object. Not all
  29. objects of the same type have the same size; but the size cannot change
  30. after allocation. (These restrictions are made so a reference to an
  31. object can be simply a pointer -- moving an object would require
  32. updating all the pointers, and changing an object's size would require
  33. moving it if there was another object right next to it.)
  34. Objects are always accessed through pointers of the type 'PyObject *'.
  35. The type 'PyObject' is a structure that only contains the reference count
  36. and the type pointer. The actual memory allocated for an object
  37. contains other data that can only be accessed after casting the pointer
  38. to a pointer to a longer structure type. This longer type must start
  39. with the reference count and type fields; the macro PyObject_HEAD should be
  40. used for this (to accommodate for future changes). The implementation
  41. of a particular object type can cast the object pointer to the proper
  42. type and back.
  43. A standard interface exists for objects that contain an array of items
  44. whose size is determined when the object is allocated.
  45. */
  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_REF_DEBUG)
  51. #error Py_LIMITED_API is incompatible with Py_DEBUG, Py_TRACE_REFS, and Py_REF_DEBUG
  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. struct _object *_ob_next; \
  57. struct _object *_ob_prev;
  58. #define _PyObject_EXTRA_INIT 0, 0,
  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. #define PyObject_HEAD_INIT(type) \
  66. { _PyObject_EXTRA_INIT \
  67. 1, type },
  68. #define PyVarObject_HEAD_INIT(type, size) \
  69. { PyObject_HEAD_INIT(type) size },
  70. /* PyObject_VAR_HEAD defines the initial segment of all variable-size
  71. * container objects. These end with a declaration of an array with 1
  72. * element, but enough space is malloc'ed so that the array actually
  73. * has room for ob_size elements. Note that ob_size is an element count,
  74. * not necessarily a byte count.
  75. */
  76. #define PyObject_VAR_HEAD PyVarObject ob_base;
  77. #define Py_INVALID_SIZE (Py_ssize_t)-1
  78. /* Nothing is actually declared to be a PyObject, but every pointer to
  79. * a Python object can be cast to a PyObject*. This is inheritance built
  80. * by hand. Similarly every pointer to a variable-size Python object can,
  81. * in addition, be cast to PyVarObject*.
  82. */
  83. typedef struct _object {
  84. _PyObject_HEAD_EXTRA
  85. Py_ssize_t ob_refcnt;
  86. struct _typeobject *ob_type;
  87. } PyObject;
  88. /* Cast argument to PyObject* type. */
  89. #define _PyObject_CAST(op) ((PyObject*)(op))
  90. typedef struct {
  91. PyObject ob_base;
  92. Py_ssize_t ob_size; /* Number of items in variable part */
  93. } PyVarObject;
  94. /* Cast argument to PyVarObject* type. */
  95. #define _PyVarObject_CAST(op) ((PyVarObject*)(op))
  96. #define Py_REFCNT(ob) (_PyObject_CAST(ob)->ob_refcnt)
  97. #define Py_TYPE(ob) (_PyObject_CAST(ob)->ob_type)
  98. #define Py_SIZE(ob) (_PyVarObject_CAST(ob)->ob_size)
  99. /*
  100. Type objects contain a string containing the type name (to help somewhat
  101. in debugging), the allocation parameters (see PyObject_New() and
  102. PyObject_NewVar()),
  103. and methods for accessing objects of the type. Methods are optional, a
  104. nil pointer meaning that particular kind of access is not available for
  105. this type. The Py_DECREF() macro uses the tp_dealloc method without
  106. checking for a nil pointer; it should always be implemented except if
  107. the implementation can guarantee that the reference count will never
  108. reach zero (e.g., for statically allocated type objects).
  109. NB: the methods for certain type groups are now contained in separate
  110. method blocks.
  111. */
  112. typedef PyObject * (*unaryfunc)(PyObject *);
  113. typedef PyObject * (*binaryfunc)(PyObject *, PyObject *);
  114. typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *);
  115. typedef int (*inquiry)(PyObject *);
  116. typedef Py_ssize_t (*lenfunc)(PyObject *);
  117. typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t);
  118. typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t);
  119. typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *);
  120. typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
  121. typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
  122. typedef int (*objobjproc)(PyObject *, PyObject *);
  123. typedef int (*visitproc)(PyObject *, void *);
  124. typedef int (*traverseproc)(PyObject *, visitproc, void *);
  125. typedef void (*freefunc)(void *);
  126. typedef void (*destructor)(PyObject *);
  127. typedef PyObject *(*getattrfunc)(PyObject *, char *);
  128. typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
  129. typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
  130. typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *);
  131. typedef PyObject *(*reprfunc)(PyObject *);
  132. typedef Py_hash_t (*hashfunc)(PyObject *);
  133. typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int);
  134. typedef PyObject *(*getiterfunc) (PyObject *);
  135. typedef PyObject *(*iternextfunc) (PyObject *);
  136. typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *);
  137. typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *);
  138. typedef int (*initproc)(PyObject *, PyObject *, PyObject *);
  139. typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *);
  140. typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t);
  141. #ifdef Py_LIMITED_API
  142. /* In Py_LIMITED_API, PyTypeObject is an opaque structure. */
  143. typedef struct _typeobject PyTypeObject;
  144. #else
  145. /* PyTypeObject is defined in cpython/object.h */
  146. #endif
  147. typedef struct{
  148. int slot; /* slot id, see below */
  149. void *pfunc; /* function pointer */
  150. } PyType_Slot;
  151. typedef struct{
  152. const char* name;
  153. int basicsize;
  154. int itemsize;
  155. unsigned int flags;
  156. PyType_Slot *slots; /* terminated by slot==0. */
  157. } PyType_Spec;
  158. PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
  159. #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
  160. PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*);
  161. #endif
  162. #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000
  163. PyAPI_FUNC(void*) PyType_GetSlot(struct _typeobject*, int);
  164. #endif
  165. /* Generic type check */
  166. PyAPI_FUNC(int) PyType_IsSubtype(struct _typeobject *, struct _typeobject *);
  167. #define PyObject_TypeCheck(ob, tp) \
  168. (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
  169. PyAPI_DATA(struct _typeobject) PyType_Type; /* built-in 'type' */
  170. PyAPI_DATA(struct _typeobject) PyBaseObject_Type; /* built-in 'object' */
  171. PyAPI_DATA(struct _typeobject) PySuper_Type; /* built-in 'super' */
  172. PyAPI_FUNC(unsigned long) PyType_GetFlags(struct _typeobject*);
  173. #define PyType_Check(op) \
  174. PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS)
  175. #define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)
  176. PyAPI_FUNC(int) PyType_Ready(struct _typeobject *);
  177. PyAPI_FUNC(PyObject *) PyType_GenericAlloc(struct _typeobject *, Py_ssize_t);
  178. PyAPI_FUNC(PyObject *) PyType_GenericNew(struct _typeobject *,
  179. PyObject *, PyObject *);
  180. PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
  181. PyAPI_FUNC(void) PyType_Modified(struct _typeobject *);
  182. /* Generic operations on objects */
  183. PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
  184. PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
  185. PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
  186. PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *);
  187. PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int);
  188. PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int);
  189. PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *);
  190. PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *);
  191. PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *);
  192. PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
  193. PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
  194. PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
  195. PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
  196. PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
  197. PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
  198. PyObject *, PyObject *);
  199. #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000
  200. PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *);
  201. #endif
  202. PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *);
  203. PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *);
  204. PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
  205. PyAPI_FUNC(int) PyObject_Not(PyObject *);
  206. PyAPI_FUNC(int) PyCallable_Check(PyObject *);
  207. PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *);
  208. /* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a
  209. list of strings. PyObject_Dir(NULL) is like builtins.dir(),
  210. returning the names of the current locals. In this case, if there are
  211. no current locals, NULL is returned, and PyErr_Occurred() is false.
  212. */
  213. PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *);
  214. /* Helpers for printing recursive container types */
  215. PyAPI_FUNC(int) Py_ReprEnter(PyObject *);
  216. PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
  217. /* Flag bits for printing: */
  218. #define Py_PRINT_RAW 1 /* No string quotes etc. */
  219. /*
  220. Type flags (tp_flags)
  221. These flags are used to change expected features and behavior for a
  222. particular type.
  223. Arbitration of the flag bit positions will need to be coordinated among
  224. all extension writers who publicly release their extensions (this will
  225. be fewer than you might expect!).
  226. Most flags were removed as of Python 3.0 to make room for new flags. (Some
  227. flags are not for backwards compatibility but to indicate the presence of an
  228. optional feature; these flags remain of course.)
  229. Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value.
  230. Code can use PyType_HasFeature(type_ob, flag_value) to test whether the
  231. given type object has a specified feature.
  232. */
  233. /* Set if the type object is dynamically allocated */
  234. #define Py_TPFLAGS_HEAPTYPE (1UL << 9)
  235. /* Set if the type allows subclassing */
  236. #define Py_TPFLAGS_BASETYPE (1UL << 10)
  237. /* Set if the type implements the vectorcall protocol (PEP 590) */
  238. #ifndef Py_LIMITED_API
  239. #define _Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11)
  240. #endif
  241. /* Set if the type is 'ready' -- fully initialized */
  242. #define Py_TPFLAGS_READY (1UL << 12)
  243. /* Set while the type is being 'readied', to prevent recursive ready calls */
  244. #define Py_TPFLAGS_READYING (1UL << 13)
  245. /* Objects support garbage collection (see objimpl.h) */
  246. #define Py_TPFLAGS_HAVE_GC (1UL << 14)
  247. /* These two bits are preserved for Stackless Python, next after this is 17 */
  248. #ifdef STACKLESS
  249. #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15)
  250. #else
  251. #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0
  252. #endif
  253. /* Objects behave like an unbound method */
  254. #define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17)
  255. /* Objects support type attribute cache */
  256. #define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18)
  257. #define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19)
  258. /* Type is abstract and cannot be instantiated */
  259. #define Py_TPFLAGS_IS_ABSTRACT (1UL << 20)
  260. /* These flags are used to determine if a type is a subclass. */
  261. #define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24)
  262. #define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25)
  263. #define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26)
  264. #define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27)
  265. #define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28)
  266. #define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29)
  267. #define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30)
  268. #define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31)
  269. #define Py_TPFLAGS_DEFAULT ( \
  270. Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
  271. Py_TPFLAGS_HAVE_VERSION_TAG | \
  272. 0)
  273. /* NOTE: The following flags reuse lower bits (removed as part of the
  274. * Python 3.0 transition). */
  275. /* The following flag is kept for compatibility. Starting with 3.8,
  276. * binary compatibility of C extensions accross feature releases of
  277. * Python is not supported anymore, except when using the stable ABI.
  278. */
  279. /* Type structure has tp_finalize member (3.4) */
  280. #define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0)
  281. #ifdef Py_LIMITED_API
  282. # define PyType_HasFeature(t,f) ((PyType_GetFlags(t) & (f)) != 0)
  283. #endif
  284. #define PyType_FastSubclass(t,f) PyType_HasFeature(t,f)
  285. /*
  286. The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement
  287. reference counts. Py_DECREF calls the object's deallocator function when
  288. the refcount falls to 0; for
  289. objects that don't contain references to other objects or heap memory
  290. this can be the standard function free(). Both macros can be used
  291. wherever a void expression is allowed. The argument must not be a
  292. NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead.
  293. The macro _Py_NewReference(op) initialize reference counts to 1, and
  294. in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional
  295. bookkeeping appropriate to the special build.
  296. We assume that the reference count field can never overflow; this can
  297. be proven when the size of the field is the same as the pointer size, so
  298. we ignore the possibility. Provided a C int is at least 32 bits (which
  299. is implicitly assumed in many parts of this code), that's enough for
  300. about 2**31 references to an object.
  301. XXX The following became out of date in Python 2.2, but I'm not sure
  302. XXX what the full truth is now. Certainly, heap-allocated type objects
  303. XXX can and should be deallocated.
  304. Type objects should never be deallocated; the type pointer in an object
  305. is not considered to be a reference to the type object, to save
  306. complications in the deallocation function. (This is actually a
  307. decision that's up to the implementer of each new type so if you want,
  308. you can count such references to the type object.)
  309. */
  310. /* First define a pile of simple helper macros, one set per special
  311. * build symbol. These either expand to the obvious things, or to
  312. * nothing at all when the special mode isn't in effect. The main
  313. * macros can later be defined just once then, yet expand to different
  314. * things depending on which special build options are and aren't in effect.
  315. * Trust me <wink>: while painful, this is 20x easier to understand than,
  316. * e.g, defining _Py_NewReference five different times in a maze of nested
  317. * #ifdefs (we used to do that -- it was impenetrable).
  318. */
  319. #ifdef Py_REF_DEBUG
  320. PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
  321. PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno,
  322. PyObject *op);
  323. PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
  324. #define _Py_INC_REFTOTAL _Py_RefTotal++
  325. #define _Py_DEC_REFTOTAL _Py_RefTotal--
  326. /* Py_REF_DEBUG also controls the display of refcounts and memory block
  327. * allocations at the interactive prompt and at interpreter shutdown
  328. */
  329. PyAPI_FUNC(void) _PyDebug_PrintTotalRefs(void);
  330. #else
  331. #define _Py_INC_REFTOTAL
  332. #define _Py_DEC_REFTOTAL
  333. #endif /* Py_REF_DEBUG */
  334. #ifdef COUNT_ALLOCS
  335. PyAPI_FUNC(void) _Py_inc_count(struct _typeobject *);
  336. PyAPI_FUNC(void) _Py_dec_count(struct _typeobject *);
  337. #define _Py_INC_TPALLOCS(OP) _Py_inc_count(Py_TYPE(OP))
  338. #define _Py_INC_TPFREES(OP) _Py_dec_count(Py_TYPE(OP))
  339. #define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees--
  340. #define _Py_COUNT_ALLOCS_COMMA ,
  341. #else
  342. #define _Py_INC_TPALLOCS(OP)
  343. #define _Py_INC_TPFREES(OP)
  344. #define _Py_DEC_TPFREES(OP)
  345. #define _Py_COUNT_ALLOCS_COMMA
  346. #endif /* COUNT_ALLOCS */
  347. /* Update the Python traceback of an object. This function must be called
  348. when a memory block is reused from a free list. */
  349. PyAPI_FUNC(int) _PyTraceMalloc_NewReference(PyObject *op);
  350. #ifdef Py_TRACE_REFS
  351. /* Py_TRACE_REFS is such major surgery that we call external routines. */
  352. PyAPI_FUNC(void) _Py_NewReference(PyObject *);
  353. PyAPI_FUNC(void) _Py_ForgetReference(PyObject *);
  354. PyAPI_FUNC(void) _Py_PrintReferences(FILE *);
  355. PyAPI_FUNC(void) _Py_PrintReferenceAddresses(FILE *);
  356. PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
  357. #else
  358. /* Without Py_TRACE_REFS, there's little enough to do that we expand code
  359. inline. */
  360. static inline void _Py_NewReference(PyObject *op)
  361. {
  362. if (_Py_tracemalloc_config.tracing) {
  363. _PyTraceMalloc_NewReference(op);
  364. }
  365. _Py_INC_TPALLOCS(op);
  366. _Py_INC_REFTOTAL;
  367. Py_REFCNT(op) = 1;
  368. }
  369. static inline void _Py_ForgetReference(PyObject *op)
  370. {
  371. (void)op; /* may be unused, shut up -Wunused-parameter */
  372. _Py_INC_TPFREES(op);
  373. }
  374. #endif /* !Py_TRACE_REFS */
  375. PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
  376. static inline void _Py_INCREF(PyObject *op)
  377. {
  378. _Py_INC_REFTOTAL;
  379. op->ob_refcnt++;
  380. }
  381. #define Py_INCREF(op) _Py_INCREF(_PyObject_CAST(op))
  382. static inline void _Py_DECREF(const char *filename, int lineno,
  383. PyObject *op)
  384. {
  385. (void)filename; /* may be unused, shut up -Wunused-parameter */
  386. (void)lineno; /* may be unused, shut up -Wunused-parameter */
  387. _Py_DEC_REFTOTAL;
  388. if (--op->ob_refcnt != 0) {
  389. #ifdef Py_REF_DEBUG
  390. if (op->ob_refcnt < 0) {
  391. _Py_NegativeRefcount(filename, lineno, op);
  392. }
  393. #endif
  394. }
  395. else {
  396. _Py_Dealloc(op);
  397. }
  398. }
  399. #define Py_DECREF(op) _Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op))
  400. /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
  401. * and tp_dealloc implementations.
  402. *
  403. * Note that "the obvious" code can be deadly:
  404. *
  405. * Py_XDECREF(op);
  406. * op = NULL;
  407. *
  408. * Typically, `op` is something like self->containee, and `self` is done
  409. * using its `containee` member. In the code sequence above, suppose
  410. * `containee` is non-NULL with a refcount of 1. Its refcount falls to
  411. * 0 on the first line, which can trigger an arbitrary amount of code,
  412. * possibly including finalizers (like __del__ methods or weakref callbacks)
  413. * coded in Python, which in turn can release the GIL and allow other threads
  414. * to run, etc. Such code may even invoke methods of `self` again, or cause
  415. * cyclic gc to trigger, but-- oops! --self->containee still points to the
  416. * object being torn down, and it may be in an insane state while being torn
  417. * down. This has in fact been a rich historic source of miserable (rare &
  418. * hard-to-diagnose) segfaulting (and other) bugs.
  419. *
  420. * The safe way is:
  421. *
  422. * Py_CLEAR(op);
  423. *
  424. * That arranges to set `op` to NULL _before_ decref'ing, so that any code
  425. * triggered as a side-effect of `op` getting torn down no longer believes
  426. * `op` points to a valid object.
  427. *
  428. * There are cases where it's safe to use the naive code, but they're brittle.
  429. * For example, if `op` points to a Python integer, you know that destroying
  430. * one of those can't cause problems -- but in part that relies on that
  431. * Python integers aren't currently weakly referencable. Best practice is
  432. * to use Py_CLEAR() even if you can't think of a reason for why you need to.
  433. */
  434. #define Py_CLEAR(op) \
  435. do { \
  436. PyObject *_py_tmp = _PyObject_CAST(op); \
  437. if (_py_tmp != NULL) { \
  438. (op) = NULL; \
  439. Py_DECREF(_py_tmp); \
  440. } \
  441. } while (0)
  442. /* Function to use in case the object pointer can be NULL: */
  443. static inline void _Py_XINCREF(PyObject *op)
  444. {
  445. if (op != NULL) {
  446. Py_INCREF(op);
  447. }
  448. }
  449. #define Py_XINCREF(op) _Py_XINCREF(_PyObject_CAST(op))
  450. static inline void _Py_XDECREF(PyObject *op)
  451. {
  452. if (op != NULL) {
  453. Py_DECREF(op);
  454. }
  455. }
  456. #define Py_XDECREF(op) _Py_XDECREF(_PyObject_CAST(op))
  457. /*
  458. These are provided as conveniences to Python runtime embedders, so that
  459. they can have object code that is not dependent on Python compilation flags.
  460. */
  461. PyAPI_FUNC(void) Py_IncRef(PyObject *);
  462. PyAPI_FUNC(void) Py_DecRef(PyObject *);
  463. /*
  464. _Py_NoneStruct is an object of undefined type which can be used in contexts
  465. where NULL (nil) is not suitable (since NULL often means 'error').
  466. Don't forget to apply Py_INCREF() when returning this value!!!
  467. */
  468. PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */
  469. #define Py_None (&_Py_NoneStruct)
  470. /* Macro for returning Py_None from a function */
  471. #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
  472. /*
  473. Py_NotImplemented is a singleton used to signal that an operation is
  474. not implemented for a given type combination.
  475. */
  476. PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */
  477. #define Py_NotImplemented (&_Py_NotImplementedStruct)
  478. /* Macro for returning Py_NotImplemented from a function */
  479. #define Py_RETURN_NOTIMPLEMENTED \
  480. return Py_INCREF(Py_NotImplemented), Py_NotImplemented
  481. /* Rich comparison opcodes */
  482. #define Py_LT 0
  483. #define Py_LE 1
  484. #define Py_EQ 2
  485. #define Py_NE 3
  486. #define Py_GT 4
  487. #define Py_GE 5
  488. /*
  489. * Macro for implementing rich comparisons
  490. *
  491. * Needs to be a macro because any C-comparable type can be used.
  492. */
  493. #define Py_RETURN_RICHCOMPARE(val1, val2, op) \
  494. do { \
  495. switch (op) { \
  496. case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  497. case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  498. case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  499. case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  500. case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  501. case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \
  502. default: \
  503. Py_UNREACHABLE(); \
  504. } \
  505. } while (0)
  506. /*
  507. More conventions
  508. ================
  509. Argument Checking
  510. -----------------
  511. Functions that take objects as arguments normally don't check for nil
  512. arguments, but they do check the type of the argument, and return an
  513. error if the function doesn't apply to the type.
  514. Failure Modes
  515. -------------
  516. Functions may fail for a variety of reasons, including running out of
  517. memory. This is communicated to the caller in two ways: an error string
  518. is set (see errors.h), and the function result differs: functions that
  519. normally return a pointer return NULL for failure, functions returning
  520. an integer return -1 (which could be a legal return value too!), and
  521. other functions return 0 for success and -1 for failure.
  522. Callers should always check for errors before using the result. If
  523. an error was set, the caller must either explicitly clear it, or pass
  524. the error on to its caller.
  525. Reference Counts
  526. ----------------
  527. It takes a while to get used to the proper usage of reference counts.
  528. Functions that create an object set the reference count to 1; such new
  529. objects must be stored somewhere or destroyed again with Py_DECREF().
  530. Some functions that 'store' objects, such as PyTuple_SetItem() and
  531. PyList_SetItem(),
  532. don't increment the reference count of the object, since the most
  533. frequent use is to store a fresh object. Functions that 'retrieve'
  534. objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also
  535. don't increment
  536. the reference count, since most frequently the object is only looked at
  537. quickly. Thus, to retrieve an object and store it again, the caller
  538. must call Py_INCREF() explicitly.
  539. NOTE: functions that 'consume' a reference count, like
  540. PyList_SetItem(), consume the reference even if the object wasn't
  541. successfully stored, to simplify error handling.
  542. It seems attractive to make other functions that take an object as
  543. argument consume a reference count; however, this may quickly get
  544. confusing (even the current practice is already confusing). Consider
  545. it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at
  546. times.
  547. */
  548. /* Trashcan mechanism, thanks to Christian Tismer.
  549. When deallocating a container object, it's possible to trigger an unbounded
  550. chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
  551. next" object in the chain to 0. This can easily lead to stack overflows,
  552. especially in threads (which typically have less stack space to work with).
  553. A container object can avoid this by bracketing the body of its tp_dealloc
  554. function with a pair of macros:
  555. static void
  556. mytype_dealloc(mytype *p)
  557. {
  558. ... declarations go here ...
  559. PyObject_GC_UnTrack(p); // must untrack first
  560. Py_TRASHCAN_BEGIN(p, mytype_dealloc)
  561. ... The body of the deallocator goes here, including all calls ...
  562. ... to Py_DECREF on contained objects. ...
  563. Py_TRASHCAN_END // there should be no code after this
  564. }
  565. CAUTION: Never return from the middle of the body! If the body needs to
  566. "get out early", put a label immediately before the Py_TRASHCAN_END
  567. call, and goto it. Else the call-depth counter (see below) will stay
  568. above 0 forever, and the trashcan will never get emptied.
  569. How it works: The BEGIN macro increments a call-depth counter. So long
  570. as this counter is small, the body of the deallocator is run directly without
  571. further ado. But if the counter gets large, it instead adds p to a list of
  572. objects to be deallocated later, skips the body of the deallocator, and
  573. resumes execution after the END macro. The tp_dealloc routine then returns
  574. without deallocating anything (and so unbounded call-stack depth is avoided).
  575. When the call stack finishes unwinding again, code generated by the END macro
  576. notices this, and calls another routine to deallocate all the objects that
  577. may have been added to the list of deferred deallocations. In effect, a
  578. chain of N deallocations is broken into (N-1)/(PyTrash_UNWIND_LEVEL-1) pieces,
  579. with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL.
  580. Since the tp_dealloc of a subclass typically calls the tp_dealloc of the base
  581. class, we need to ensure that the trashcan is only triggered on the tp_dealloc
  582. of the actual class being deallocated. Otherwise we might end up with a
  583. partially-deallocated object. To check this, the tp_dealloc function must be
  584. passed as second argument to Py_TRASHCAN_BEGIN().
  585. */
  586. /* The new thread-safe private API, invoked by the macros below. */
  587. PyAPI_FUNC(void) _PyTrash_thread_deposit_object(PyObject*);
  588. PyAPI_FUNC(void) _PyTrash_thread_destroy_chain(void);
  589. #define PyTrash_UNWIND_LEVEL 50
  590. #define Py_TRASHCAN_BEGIN_CONDITION(op, cond) \
  591. do { \
  592. PyThreadState *_tstate = NULL; \
  593. /* If "cond" is false, then _tstate remains NULL and the deallocator \
  594. * is run normally without involving the trashcan */ \
  595. if (cond) { \
  596. _tstate = PyThreadState_GET(); \
  597. if (_tstate->trash_delete_nesting >= PyTrash_UNWIND_LEVEL) { \
  598. /* Store the object (to be deallocated later) and jump past \
  599. * Py_TRASHCAN_END, skipping the body of the deallocator */ \
  600. _PyTrash_thread_deposit_object(_PyObject_CAST(op)); \
  601. break; \
  602. } \
  603. ++_tstate->trash_delete_nesting; \
  604. }
  605. /* The body of the deallocator is here. */
  606. #define Py_TRASHCAN_END \
  607. if (_tstate) { \
  608. --_tstate->trash_delete_nesting; \
  609. if (_tstate->trash_delete_later && _tstate->trash_delete_nesting <= 0) \
  610. _PyTrash_thread_destroy_chain(); \
  611. } \
  612. } while (0);
  613. #define Py_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN_CONDITION(op, \
  614. Py_TYPE(op)->tp_dealloc == (destructor)(dealloc))
  615. /* For backwards compatibility, these macros enable the trashcan
  616. * unconditionally */
  617. #define Py_TRASHCAN_SAFE_BEGIN(op) Py_TRASHCAN_BEGIN_CONDITION(op, 1)
  618. #define Py_TRASHCAN_SAFE_END(op) Py_TRASHCAN_END
  619. #ifndef Py_LIMITED_API
  620. # define Py_CPYTHON_OBJECT_H
  621. # include "cpython/object.h"
  622. # undef Py_CPYTHON_OBJECT_H
  623. #endif
  624. #ifdef __cplusplus
  625. }
  626. #endif
  627. #endif /* !Py_OBJECT_H */