blob: 3e612825c27775dbb24e8dfab9dfc0440e37bbae [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Benjamin Peterson722954a2011-06-11 16:33:35 -05002/* Generic object operations; and implementation of None */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Victor Stinnerbe434dc2019-11-05 00:51:22 +01005#include "pycore_context.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02006#include "pycore_initconfig.h"
Victor Stinner0fc91ee2019-04-12 21:51:34 +02007#include "pycore_object.h"
Victor Stinnerbe434dc2019-11-05 00:51:22 +01008#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pystate.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +000010#include "frameobject.h"
Eric Snowc11183c2019-03-15 16:35:46 -060011#include "interpreteridobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013#ifdef __cplusplus
14extern "C" {
15#endif
16
Victor Stinner626bff82018-10-25 17:31:10 +020017/* Defined in tracemalloc.c */
18extern void _PyMem_DumpTraceback(int fd, const void *ptr);
19
Victor Stinnerbd303c12013-11-07 23:07:29 +010020_Py_IDENTIFIER(Py_Repr);
21_Py_IDENTIFIER(__bytes__);
22_Py_IDENTIFIER(__dir__);
23_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010024
Victor Stinner0fc91ee2019-04-12 21:51:34 +020025
26int
27_PyObject_CheckConsistency(PyObject *op, int check_content)
28{
Victor Stinner68762572019-10-07 18:42:01 +020029#define CHECK(expr) \
30 do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
Victor Stinner0fc91ee2019-04-12 21:51:34 +020031
Victor Stinner68762572019-10-07 18:42:01 +020032 CHECK(!_PyObject_IsFreed(op));
33 CHECK(Py_REFCNT(op) >= 1);
34
35 CHECK(op->ob_type != NULL);
36 _PyType_CheckConsistency(op->ob_type);
Victor Stinner0fc91ee2019-04-12 21:51:34 +020037
38 if (PyUnicode_Check(op)) {
39 _PyUnicode_CheckConsistency(op, check_content);
40 }
41 else if (PyDict_Check(op)) {
42 _PyDict_CheckConsistency(op, check_content);
43 }
44 return 1;
Victor Stinner68762572019-10-07 18:42:01 +020045
46#undef CHECK
Victor Stinner0fc91ee2019-04-12 21:51:34 +020047}
48
49
Tim Peters34592512002-07-11 06:23:50 +000050#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000051Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000052
53Py_ssize_t
54_Py_GetRefTotal(void)
55{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 PyObject *o;
57 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020058 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 if (o != NULL)
60 total -= o->ob_refcnt;
61 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062}
Nick Coghland6009512014-11-20 21:39:37 +100063
64void
65_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070066 fprintf(stderr,
67 "[%" PY_FORMAT_SIZE_T "d refs, "
68 "%" PY_FORMAT_SIZE_T "d blocks]\n",
69 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100070}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000071#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072
Guido van Rossum3f5da241990-12-20 15:06:42 +000073/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
74 These are used by the individual routines for object creation.
75 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000076
Tim Peters78be7992003-03-23 02:51:01 +000077#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000078/* Head of circular doubly-linked list of all objects. These are linked
79 * together via the _ob_prev and _ob_next members of a PyObject, which
80 * exist only in a Py_TRACE_REFS build.
81 */
Tim Peters78be7992003-03-23 02:51:01 +000082static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000083
Tim Peters7571a0f2003-03-23 17:52:28 +000084/* Insert op at the front of the list of all objects. If force is true,
85 * op is added even if _ob_prev and _ob_next are non-NULL already. If
86 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
87 * force should be true if and only if op points to freshly allocated,
88 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000089 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000090 * Note that objects are normally added to the list via _Py_NewReference,
91 * which is called by PyObject_Init. Not all objects are initialized that
92 * way, though; exceptions include statically allocated type objects, and
93 * statically allocated singletons (like Py_True and Py_None).
94 */
Tim Peters36eb4df2003-03-23 03:33:13 +000095void
Tim Peters7571a0f2003-03-23 17:52:28 +000096_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000097{
Tim Peters7571a0f2003-03-23 17:52:28 +000098#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 if (!force) {
100 /* If it's initialized memory, op must be in or out of
101 * the list unambiguously.
102 */
Victor Stinner24702042018-10-26 17:16:37 +0200103 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 }
Tim Peters78be7992003-03-23 02:51:01 +0000105#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 if (force || op->_ob_prev == NULL) {
107 op->_ob_next = refchain._ob_next;
108 op->_ob_prev = &refchain;
109 refchain._ob_next->_ob_prev = op;
110 refchain._ob_next = op;
111 }
Tim Peters7571a0f2003-03-23 17:52:28 +0000112}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +0000114
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000115#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000117/* All types are added to type_list, at least when
118 they get one object created. That makes them
119 immortal, which unfortunately contributes to
120 garbage itself. If unlist_types_without_objects
121 is set, they will be removed from the type_list
122 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +0000123static int unlist_types_without_objects;
Pablo Galindo49c75a82018-10-28 15:02:17 +0000124extern Py_ssize_t _Py_tuple_zero_allocs, _Py_fast_tuple_allocs;
125extern Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
126extern Py_ssize_t _Py_null_strings, _Py_one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000127void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000128_Py_dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000129{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200130 PyInterpreterState *interp = _PyInterpreterState_Get();
Victor Stinner331a6a52019-05-27 16:39:22 +0200131 if (!interp->config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300132 return;
Victor Stinner25420fe2017-11-20 18:12:22 -0800133 }
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000134
Eddie Elizondo745dc652018-02-21 20:55:18 -0800135 PyTypeObject *tp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 for (tp = type_list; tp; tp = tp->tp_next)
137 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
138 "freed: %" PY_FORMAT_SIZE_T "d, "
139 "max in use: %" PY_FORMAT_SIZE_T "d\n",
140 tp->tp_name, tp->tp_allocs, tp->tp_frees,
141 tp->tp_maxalloc);
142 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
143 "empty: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000144 _Py_fast_tuple_allocs, _Py_tuple_zero_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
146 "neg: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000147 _Py_quick_int_allocs, _Py_quick_neg_int_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
149 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000150 _Py_null_strings, _Py_one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000151}
152
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000153PyObject *
Pablo Galindo49c75a82018-10-28 15:02:17 +0000154_Py_get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 PyTypeObject *tp;
157 PyObject *result;
158 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 result = PyList_New(0);
161 if (result == NULL)
162 return NULL;
163 for (tp = type_list; tp; tp = tp->tp_next) {
164 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
165 tp->tp_frees, tp->tp_maxalloc);
166 if (v == NULL) {
167 Py_DECREF(result);
168 return NULL;
169 }
170 if (PyList_Append(result, v) < 0) {
171 Py_DECREF(v);
172 Py_DECREF(result);
173 return NULL;
174 }
175 Py_DECREF(v);
176 }
177 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000178}
179
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000180void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000181_Py_inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
184 /* first time; insert in linked list */
185 if (tp->tp_next != NULL) /* sanity check */
Pablo Galindo49c75a82018-10-28 15:02:17 +0000186 Py_FatalError("XXX _Py_inc_count sanity check");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (type_list)
188 type_list->tp_prev = tp;
189 tp->tp_next = type_list;
190 /* Note that as of Python 2.2, heap-allocated type objects
191 * can go away, but this code requires that they stay alive
192 * until program exit. That's why we're careful with
193 * refcounts here. type_list gets a new reference to tp,
194 * while ownership of the reference type_list used to hold
195 * (if any) was transferred to tp->tp_next in the line above.
196 * tp is thus effectively immortal after this.
197 */
198 Py_INCREF(tp);
199 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000200#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 /* Also insert in the doubly-linked list of all objects,
202 * if not already there.
203 */
204 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000205#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 }
207 tp->tp_allocs++;
208 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
209 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000210}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211
Pablo Galindo49c75a82018-10-28 15:02:17 +0000212void _Py_dec_count(PyTypeObject *tp)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 tp->tp_frees++;
215 if (unlist_types_without_objects &&
216 tp->tp_allocs == tp->tp_frees) {
217 /* unlink the type from type_list */
218 if (tp->tp_prev)
219 tp->tp_prev->tp_next = tp->tp_next;
220 else
221 type_list = tp->tp_next;
222 if (tp->tp_next)
223 tp->tp_next->tp_prev = tp->tp_prev;
224 tp->tp_next = tp->tp_prev = NULL;
225 Py_DECREF(tp);
226 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000227}
228
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000229#endif
230
Tim Peters7c321a82002-07-09 02:57:01 +0000231#ifdef Py_REF_DEBUG
232/* Log a fatal error; doesn't return. */
233void
Victor Stinner18618e652018-10-25 17:28:11 +0200234_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000235{
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100236 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200237 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000238}
239
240#endif /* Py_REF_DEBUG */
241
Thomas Heller1328b522004-04-22 17:23:49 +0000242void
243Py_IncRef(PyObject *o)
244{
245 Py_XINCREF(o);
246}
247
248void
249Py_DecRef(PyObject *o)
250{
251 Py_XDECREF(o);
252}
253
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000254PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000255PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (op == NULL)
258 return PyErr_NoMemory();
259 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
260 Py_TYPE(op) = tp;
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400261 if (PyType_GetFlags(tp) & Py_TPFLAGS_HEAPTYPE) {
262 Py_INCREF(tp);
263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 _Py_NewReference(op);
265 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000266}
267
Guido van Rossumb18618d2000-05-03 23:44:39 +0000268PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000269PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (op == NULL)
272 return (PyVarObject *) PyErr_NoMemory();
273 /* Any changes should be reflected in PyObject_INIT_VAR */
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400274 Py_SIZE(op) = size;
275 PyObject_Init((PyObject *)op, tp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000277}
278
279PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000280_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 PyObject *op;
283 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
284 if (op == NULL)
285 return PyErr_NoMemory();
286 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000287}
288
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000289PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000290_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 PyVarObject *op;
293 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
294 op = (PyVarObject *) PyObject_MALLOC(size);
295 if (op == NULL)
296 return (PyVarObject *)PyErr_NoMemory();
297 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000298}
299
Antoine Pitrou796564c2013-07-30 19:59:21 +0200300void
301PyObject_CallFinalizer(PyObject *self)
302{
303 PyTypeObject *tp = Py_TYPE(self);
304
Antoine Pitrouada319b2019-05-29 22:12:38 +0200305 if (tp->tp_finalize == NULL)
Antoine Pitrou796564c2013-07-30 19:59:21 +0200306 return;
307 /* tp_finalize should only be called once. */
308 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
309 return;
310
311 tp->tp_finalize(self);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900312 if (PyType_IS_GC(tp)) {
313 _PyGC_SET_FINALIZED(self);
314 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200315}
316
317int
318PyObject_CallFinalizerFromDealloc(PyObject *self)
319{
320 Py_ssize_t refcnt;
321
322 /* Temporarily resurrect the object. */
323 if (self->ob_refcnt != 0) {
324 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
325 "object with a non-zero refcount");
326 }
327 self->ob_refcnt = 1;
328
329 PyObject_CallFinalizer(self);
330
331 /* Undo the temporary resurrection; can't use DECREF here, it would
332 * cause a recursive call.
333 */
Victor Stinner24702042018-10-26 17:16:37 +0200334 _PyObject_ASSERT_WITH_MSG(self,
335 self->ob_refcnt > 0,
336 "refcount is too small");
Antoine Pitrou796564c2013-07-30 19:59:21 +0200337 if (--self->ob_refcnt == 0)
338 return 0; /* this is the normal path out */
339
340 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
341 * never happened.
342 */
343 refcnt = self->ob_refcnt;
344 _Py_NewReference(self);
345 self->ob_refcnt = refcnt;
346
Victor Stinner24702042018-10-26 17:16:37 +0200347 _PyObject_ASSERT(self,
348 (!PyType_IS_GC(Py_TYPE(self))
349 || _PyObject_GC_IS_TRACKED(self)));
Antoine Pitrou796564c2013-07-30 19:59:21 +0200350 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
351 * we need to undo that. */
352 _Py_DEC_REFTOTAL;
353 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
354 * chain, so no more to do there.
355 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
356 * _Py_NewReference bumped tp_allocs: both of those need to be
357 * undone.
358 */
359#ifdef COUNT_ALLOCS
360 --Py_TYPE(self)->tp_frees;
361 --Py_TYPE(self)->tp_allocs;
362#endif
363 return -1;
364}
365
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000366int
367PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (PyErr_CheckSignals())
371 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000372#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (PyOS_CheckStack()) {
374 PyErr_SetString(PyExc_MemoryError, "stack overflow");
375 return -1;
376 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000377#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 clearerr(fp); /* Clear any previous error condition */
379 if (op == NULL) {
380 Py_BEGIN_ALLOW_THREADS
381 fprintf(fp, "<nil>");
382 Py_END_ALLOW_THREADS
383 }
384 else {
Victor Stinner3ec9af72018-10-26 02:12:34 +0200385 if (op->ob_refcnt <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* XXX(twouters) cast refcount to long until %zd is
387 universally available */
388 Py_BEGIN_ALLOW_THREADS
389 fprintf(fp, "<refcnt %ld at %p>",
Zackery Spytz1a2252e2019-05-06 10:56:51 -0600390 (long)op->ob_refcnt, (void *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200392 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 else {
394 PyObject *s;
395 if (flags & Py_PRINT_RAW)
396 s = PyObject_Str(op);
397 else
398 s = PyObject_Repr(op);
399 if (s == NULL)
400 ret = -1;
401 else if (PyBytes_Check(s)) {
402 fwrite(PyBytes_AS_STRING(s), 1,
403 PyBytes_GET_SIZE(s), fp);
404 }
405 else if (PyUnicode_Check(s)) {
406 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200407 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600408 if (t == NULL) {
409 ret = -1;
410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 else {
412 fwrite(PyBytes_AS_STRING(t), 1,
413 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000414 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
416 }
417 else {
418 PyErr_Format(PyExc_TypeError,
419 "str() or repr() returned '%.100s'",
420 s->ob_type->tp_name);
421 ret = -1;
422 }
423 Py_XDECREF(s);
424 }
425 }
426 if (ret == 0) {
427 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300428 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 clearerr(fp);
430 ret = -1;
431 }
432 }
433 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434}
435
Guido van Rossum38938152006-08-21 23:36:26 +0000436/* For debugging convenience. Set a breakpoint here and call it from your DLL */
437void
Thomas Woutersb2137042007-02-01 18:02:27 +0000438_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000439{
440}
441
Neal Norwitz1a997502003-01-13 20:13:12 +0000442
Victor Stinner4c409be2019-04-11 13:01:15 +0200443/* Heuristic checking if the object memory is uninitialized or deallocated.
444 Rely on the debug hooks on Python memory allocators:
445 see _PyMem_IsPtrFreed().
Victor Stinner82af0b62018-10-23 17:39:40 +0200446
447 The function can be used to prevent segmentation fault on dereferencing
Victor Stinner4c409be2019-04-11 13:01:15 +0200448 pointers like 0xDDDDDDDDDDDDDDDD. */
Victor Stinner82af0b62018-10-23 17:39:40 +0200449int
450_PyObject_IsFreed(PyObject *op)
451{
Victor Stinner2b00db62019-04-11 11:33:27 +0200452 if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(op->ob_type)) {
Victor Stinner2cf5d322018-11-22 16:32:57 +0100453 return 1;
454 }
Victor Stinner2b00db62019-04-11 11:33:27 +0200455 /* ignore op->ob_ref: its value can have be modified
Victor Stinner82af0b62018-10-23 17:39:40 +0200456 by Py_INCREF() and Py_DECREF(). */
457#ifdef Py_TRACE_REFS
Pablo Galindo36e33c32019-10-08 00:43:14 +0100458 if (op->_ob_next != NULL && _PyMem_IsPtrFreed(op->_ob_next)) {
Victor Stinner2b00db62019-04-11 11:33:27 +0200459 return 1;
460 }
Pablo Galindo36e33c32019-10-08 00:43:14 +0100461 if (op->_ob_prev != NULL && _PyMem_IsPtrFreed(op->_ob_prev)) {
462 return 1;
463 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200464#endif
Victor Stinner2b00db62019-04-11 11:33:27 +0200465 return 0;
Victor Stinner82af0b62018-10-23 17:39:40 +0200466}
467
468
Barry Warsaw9bf16442001-01-23 16:24:35 +0000469/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000470void
471_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000472{
Victor Stinner82af0b62018-10-23 17:39:40 +0200473 if (_PyObject_IsFreed(op)) {
474 /* It seems like the object memory has been freed:
475 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +0200476 fprintf(stderr, "<object at %p is freed>\n", op);
Victor Stinner68762572019-10-07 18:42:01 +0200477 fflush(stderr);
Victor Stinner2cf5d322018-11-22 16:32:57 +0100478 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200479 }
480
Victor Stinner68762572019-10-07 18:42:01 +0200481 /* first, write fields which are the least likely to crash */
482 fprintf(stderr, "object address : %p\n", (void *)op);
Victor Stinner82af0b62018-10-23 17:39:40 +0200483 /* XXX(twouters) cast refcount to long until %zd is
484 universally available */
Victor Stinner68762572019-10-07 18:42:01 +0200485 fprintf(stderr, "object refcount : %ld\n", (long)op->ob_refcnt);
486 fflush(stderr);
487
488 PyTypeObject *type = Py_TYPE(op);
489 fprintf(stderr, "object type : %p\n", type);
490 fprintf(stderr, "object type name: %s\n",
491 type==NULL ? "NULL" : type->tp_name);
492
493 /* the most dangerous part */
494 fprintf(stderr, "object repr : ");
495 fflush(stderr);
496
497 PyGILState_STATE gil = PyGILState_Ensure();
498 PyObject *error_type, *error_value, *error_traceback;
499 PyErr_Fetch(&error_type, &error_value, &error_traceback);
500
501 (void)PyObject_Print(op, stderr, 0);
502 fflush(stderr);
503
504 PyErr_Restore(error_type, error_value, error_traceback);
505 PyGILState_Release(gil);
506
507 fprintf(stderr, "\n");
Victor Stinner82af0b62018-10-23 17:39:40 +0200508 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000509}
Barry Warsaw903138f2001-01-23 16:33:18 +0000510
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000512PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 PyObject *res;
515 if (PyErr_CheckSignals())
516 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000517#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 if (PyOS_CheckStack()) {
519 PyErr_SetString(PyExc_MemoryError, "stack overflow");
520 return NULL;
521 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000522#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (v == NULL)
524 return PyUnicode_FromString("<NULL>");
525 if (Py_TYPE(v)->tp_repr == NULL)
526 return PyUnicode_FromFormat("<%s object at %p>",
527 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200528
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100529 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner33824f62013-08-26 14:05:19 +0200530#ifdef Py_DEBUG
531 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100532 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000533 caller loses its exception */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100534 assert(!_PyErr_Occurred(tstate));
Victor Stinner33824f62013-08-26 14:05:19 +0200535#endif
536
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200537 /* It is possible for a type to have a tp_repr representation that loops
538 infinitely. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100539 if (_Py_EnterRecursiveCall(tstate,
540 " while getting the repr of an object")) {
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200541 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 res = (*v->ob_type->tp_repr)(v);
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100544 _Py_LeaveRecursiveCall(tstate);
545
546 if (res == NULL) {
Victor Stinner0a54cf12011-12-01 03:22:44 +0100547 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100548 }
Victor Stinner0a54cf12011-12-01 03:22:44 +0100549 if (!PyUnicode_Check(res)) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100550 _PyErr_Format(tstate, PyExc_TypeError,
551 "__repr__ returned non-string (type %.200s)",
552 res->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 Py_DECREF(res);
554 return NULL;
555 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100556#ifndef Py_DEBUG
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100557 if (PyUnicode_READY(res) < 0) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100558 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100559 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100560#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000565PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyObject *res;
568 if (PyErr_CheckSignals())
569 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000570#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (PyOS_CheckStack()) {
572 PyErr_SetString(PyExc_MemoryError, "stack overflow");
573 return NULL;
574 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000575#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (v == NULL)
577 return PyUnicode_FromString("<NULL>");
578 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100579#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100580 if (PyUnicode_READY(v) < 0)
581 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100582#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 Py_INCREF(v);
584 return v;
585 }
586 if (Py_TYPE(v)->tp_str == NULL)
587 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000588
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100589 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner33824f62013-08-26 14:05:19 +0200590#ifdef Py_DEBUG
591 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100592 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000593 caller loses its exception */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100594 assert(!_PyErr_Occurred(tstate));
Victor Stinner33824f62013-08-26 14:05:19 +0200595#endif
596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 /* It is possible for a type to have a tp_str representation that loops
598 infinitely. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100599 if (_Py_EnterRecursiveCall(tstate, " while getting the str of an object")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100601 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 res = (*Py_TYPE(v)->tp_str)(v);
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100603 _Py_LeaveRecursiveCall(tstate);
604
605 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100607 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (!PyUnicode_Check(res)) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100609 _PyErr_Format(tstate, PyExc_TypeError,
610 "__str__ returned non-string (type %.200s)",
611 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 Py_DECREF(res);
613 return NULL;
614 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100615#ifndef Py_DEBUG
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100616 if (PyUnicode_READY(res) < 0) {
Victor Stinner4ead7c72011-11-20 19:48:36 +0100617 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100618 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100619#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100620 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000622}
623
Georg Brandl559e5d72008-06-11 18:37:52 +0000624PyObject *
625PyObject_ASCII(PyObject *v)
626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 repr = PyObject_Repr(v);
630 if (repr == NULL)
631 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000632
Victor Stinneraf037572013-04-14 18:44:10 +0200633 if (PyUnicode_IS_ASCII(repr))
634 return repr;
635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200637 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 Py_DECREF(repr);
639 if (ascii == NULL)
640 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 res = PyUnicode_DecodeASCII(
643 PyBytes_AS_STRING(ascii),
644 PyBytes_GET_SIZE(ascii),
645 NULL);
646
647 Py_DECREF(ascii);
648 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000649}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000650
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000651PyObject *
652PyObject_Bytes(PyObject *v)
653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (v == NULL)
657 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 if (PyBytes_CheckExact(v)) {
660 Py_INCREF(v);
661 return v;
662 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000663
Benjamin Petersonce798522012-01-22 11:24:29 -0500664 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100666 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 Py_DECREF(func);
668 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000669 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000671 PyErr_Format(PyExc_TypeError,
672 "__bytes__ returned non-bytes (type %.200s)",
673 Py_TYPE(result)->tp_name);
674 Py_DECREF(result);
675 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 }
677 return result;
678 }
679 else if (PyErr_Occurred())
680 return NULL;
681 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000682}
683
Jeroen Demeyerbf17d412019-11-05 16:48:04 +0100684
685/*
686def _PyObject_FunctionStr(x):
687 try:
688 qualname = x.__qualname__
689 except AttributeError:
690 return str(x)
691 try:
692 mod = x.__module__
693 if mod is not None and mod != 'builtins':
694 return f"{x.__module__}.{qualname}()"
695 except AttributeError:
696 pass
697 return qualname
698*/
699PyObject *
700_PyObject_FunctionStr(PyObject *x)
701{
702 _Py_IDENTIFIER(__module__);
703 _Py_IDENTIFIER(__qualname__);
704 _Py_IDENTIFIER(builtins);
705 assert(!PyErr_Occurred());
706 PyObject *qualname;
707 int ret = _PyObject_LookupAttrId(x, &PyId___qualname__, &qualname);
708 if (qualname == NULL) {
709 if (ret < 0) {
710 return NULL;
711 }
712 return PyObject_Str(x);
713 }
714 PyObject *module;
715 PyObject *result = NULL;
716 ret = _PyObject_LookupAttrId(x, &PyId___module__, &module);
717 if (module != NULL && module != Py_None) {
718 PyObject *builtinsname = _PyUnicode_FromId(&PyId_builtins);
719 if (builtinsname == NULL) {
720 goto done;
721 }
722 ret = PyObject_RichCompareBool(module, builtinsname, Py_NE);
723 if (ret < 0) {
724 // error
725 goto done;
726 }
727 if (ret > 0) {
728 result = PyUnicode_FromFormat("%S.%S()", module, qualname);
729 goto done;
730 }
731 }
732 else if (ret < 0) {
733 goto done;
734 }
735 result = PyUnicode_FromFormat("%S()", qualname);
736done:
737 Py_DECREF(qualname);
738 Py_XDECREF(module);
739 return result;
740}
741
Mark Dickinsonc008a172009-02-01 13:59:22 +0000742/* For Python 3.0.1 and later, the old three-way comparison has been
743 completely removed in favour of rich comparisons. PyObject_Compare() and
744 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200745 The old tp_compare slot has been renamed to tp_as_async, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000746 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000747
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000748 See (*) below for practical amendments.
749
Mark Dickinsonc008a172009-02-01 13:59:22 +0000750 tp_richcompare gets called with a first argument of the appropriate type
751 and a second object of an arbitrary type. We never do any kind of
752 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000753
Mark Dickinsonc008a172009-02-01 13:59:22 +0000754 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000755
756 NULL if an exception occurred
757 NotImplemented if the requested comparison is not implemented
758 any other false value if the requested comparison is false
759 any other true value if the requested comparison is true
760
761 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
762 NotImplemented.
763
764 (*) Practical amendments:
765
766 - If rich comparison returns NotImplemented, == and != are decided by
767 comparing the object pointer (i.e. falling back to the base object
768 implementation).
769
Guido van Rossuma4073002002-05-31 20:03:54 +0000770*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000771
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000772/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000773int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000774
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200775static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000776
777/* Perform a rich comparison, raising TypeError when the requested comparison
778 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000779static PyObject *
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100780do_richcompare(PyThreadState *tstate, PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 richcmpfunc f;
783 PyObject *res;
784 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (v->ob_type != w->ob_type &&
787 PyType_IsSubtype(w->ob_type, v->ob_type) &&
788 (f = w->ob_type->tp_richcompare) != NULL) {
789 checked_reverse_op = 1;
790 res = (*f)(w, v, _Py_SwappedOp[op]);
791 if (res != Py_NotImplemented)
792 return res;
793 Py_DECREF(res);
794 }
795 if ((f = v->ob_type->tp_richcompare) != NULL) {
796 res = (*f)(v, w, op);
797 if (res != Py_NotImplemented)
798 return res;
799 Py_DECREF(res);
800 }
801 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
802 res = (*f)(w, v, _Py_SwappedOp[op]);
803 if (res != Py_NotImplemented)
804 return res;
805 Py_DECREF(res);
806 }
807 /* If neither object implements it, provide a sensible default
808 for == and !=, but raise an exception for ordering. */
809 switch (op) {
810 case Py_EQ:
811 res = (v == w) ? Py_True : Py_False;
812 break;
813 case Py_NE:
814 res = (v != w) ? Py_True : Py_False;
815 break;
816 default:
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100817 _PyErr_Format(tstate, PyExc_TypeError,
818 "'%s' not supported between instances of '%.100s' and '%.100s'",
819 opstrings[op],
820 v->ob_type->tp_name,
821 w->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return NULL;
823 }
824 Py_INCREF(res);
825 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000826}
827
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000828/* Perform a rich comparison with object result. This wraps do_richcompare()
829 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000830
Guido van Rossume797ec12001-01-17 15:24:28 +0000831PyObject *
832PyObject_RichCompare(PyObject *v, PyObject *w, int op)
833{
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100834 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossume797ec12001-01-17 15:24:28 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 assert(Py_LT <= op && op <= Py_GE);
837 if (v == NULL || w == NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100838 if (!_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyErr_BadInternalCall();
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100840 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 return NULL;
842 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100843 if (_Py_EnterRecursiveCall(tstate, " in comparison")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100845 }
846 PyObject *res = do_richcompare(tstate, v, w, op);
847 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000849}
850
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000851/* Perform a rich comparison with integer result. This wraps
852 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000853int
854PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyObject *res;
857 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 /* Quick result when objects are the same.
860 Guarantees that identity implies equality. */
861 if (v == w) {
862 if (op == Py_EQ)
863 return 1;
864 else if (op == Py_NE)
865 return 0;
866 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 res = PyObject_RichCompare(v, w, op);
869 if (res == NULL)
870 return -1;
871 if (PyBool_Check(res))
872 ok = (res == Py_True);
873 else
874 ok = PyObject_IsTrue(res);
875 Py_DECREF(res);
876 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000877}
Fred Drake13634cf2000-06-29 19:17:04 +0000878
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100879Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000880PyObject_HashNotImplemented(PyObject *v)
881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
883 Py_TYPE(v)->tp_name);
884 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000885}
Fred Drake13634cf2000-06-29 19:17:04 +0000886
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000887Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000888PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 PyTypeObject *tp = Py_TYPE(v);
891 if (tp->tp_hash != NULL)
892 return (*tp->tp_hash)(v);
893 /* To keep to the general practice that inheriting
894 * solely from object in C code should work without
895 * an explicit call to PyType_Ready, we implicitly call
896 * PyType_Ready here and then check the tp_hash slot again
897 */
898 if (tp->tp_dict == NULL) {
899 if (PyType_Ready(tp) < 0)
900 return -1;
901 if (tp->tp_hash != NULL)
902 return (*tp->tp_hash)(v);
903 }
904 /* Otherwise, the object can't be hashed */
905 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000906}
907
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000908PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000909PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (Py_TYPE(v)->tp_getattr != NULL)
914 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900915 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (w == NULL)
917 return NULL;
918 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100919 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000921}
922
923int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000924PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 PyObject *res = PyObject_GetAttrString(v, name);
927 if (res != NULL) {
928 Py_DECREF(res);
929 return 1;
930 }
931 PyErr_Clear();
932 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000933}
934
935int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000936PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyObject *s;
939 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (Py_TYPE(v)->tp_setattr != NULL)
942 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
943 s = PyUnicode_InternFromString(name);
944 if (s == NULL)
945 return -1;
946 res = PyObject_SetAttr(v, s, w);
947 Py_XDECREF(s);
948 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000949}
950
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500951int
952_PyObject_IsAbstract(PyObject *obj)
953{
954 int res;
955 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500956
957 if (obj == NULL)
958 return 0;
959
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200960 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
961 if (res > 0) {
962 res = PyObject_IsTrue(isabstract);
963 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500964 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500965 return res;
966}
967
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000968PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200969_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
970{
971 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100972 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200973 if (!oname)
974 return NULL;
975 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200976 return result;
977}
978
979int
980_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
981{
982 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100983 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200984 if (!oname)
985 return -1;
986 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200987 return result;
988}
989
990int
991_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
992{
993 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100994 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200995 if (!oname)
996 return -1;
997 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200998 return result;
999}
1000
1001PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001002PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (!PyUnicode_Check(name)) {
1007 PyErr_Format(PyExc_TypeError,
1008 "attribute name must be string, not '%.200s'",
1009 name->ob_type->tp_name);
1010 return NULL;
1011 }
1012 if (tp->tp_getattro != NULL)
1013 return (*tp->tp_getattro)(v, name);
1014 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001015 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (name_str == NULL)
1017 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001018 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 }
1020 PyErr_Format(PyExc_AttributeError,
1021 "'%.50s' object has no attribute '%U'",
1022 tp->tp_name, name);
1023 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001024}
1025
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001026int
1027_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +09001028{
1029 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +09001030
1031 if (!PyUnicode_Check(name)) {
1032 PyErr_Format(PyExc_TypeError,
1033 "attribute name must be string, not '%.200s'",
1034 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001035 *result = NULL;
1036 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +09001037 }
1038
1039 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001040 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
1041 if (*result != NULL) {
1042 return 1;
1043 }
1044 if (PyErr_Occurred()) {
1045 return -1;
1046 }
1047 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +09001048 }
1049 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001050 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +09001051 }
1052 else if (tp->tp_getattr != NULL) {
1053 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001054 if (name_str == NULL) {
1055 *result = NULL;
1056 return -1;
1057 }
1058 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +09001059 }
INADA Naokie76daeb2018-01-26 16:22:51 +09001060 else {
1061 *result = NULL;
1062 return 0;
1063 }
1064
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001065 if (*result != NULL) {
1066 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +09001067 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001068 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1069 return -1;
1070 }
1071 PyErr_Clear();
1072 return 0;
1073}
1074
1075int
1076_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
1077{
1078 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
1079 if (!oname) {
1080 *result = NULL;
1081 return -1;
1082 }
1083 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +09001084}
1085
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001086int
Fred Drake100814d2000-07-09 15:48:49 +00001087PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001088{
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001089 PyObject *res;
1090 if (_PyObject_LookupAttr(v, name, &res) < 0) {
1091 PyErr_Clear();
1092 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001094 if (res == NULL) {
1095 return 0;
1096 }
1097 Py_DECREF(res);
1098 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001099}
1100
1101int
Fred Drake100814d2000-07-09 15:48:49 +00001102PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 PyTypeObject *tp = Py_TYPE(v);
1105 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (!PyUnicode_Check(name)) {
1108 PyErr_Format(PyExc_TypeError,
1109 "attribute name must be string, not '%.200s'",
1110 name->ob_type->tp_name);
1111 return -1;
1112 }
1113 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyUnicode_InternInPlace(&name);
1116 if (tp->tp_setattro != NULL) {
1117 err = (*tp->tp_setattro)(v, name, value);
1118 Py_DECREF(name);
1119 return err;
1120 }
1121 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001122 const char *name_str = PyUnicode_AsUTF8(name);
Zackery Spytze0dcb852019-04-28 06:58:52 -06001123 if (name_str == NULL) {
1124 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 return -1;
Zackery Spytze0dcb852019-04-28 06:58:52 -06001126 }
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001127 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 Py_DECREF(name);
1129 return err;
1130 }
1131 Py_DECREF(name);
Victor Stinner24702042018-10-26 17:16:37 +02001132 _PyObject_ASSERT(name, name->ob_refcnt >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1134 PyErr_Format(PyExc_TypeError,
1135 "'%.100s' object has no attributes "
1136 "(%s .%U)",
1137 tp->tp_name,
1138 value==NULL ? "del" : "assign to",
1139 name);
1140 else
1141 PyErr_Format(PyExc_TypeError,
1142 "'%.100s' object has only read-only attributes "
1143 "(%s .%U)",
1144 tp->tp_name,
1145 value==NULL ? "del" : "assign to",
1146 name);
1147 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148}
1149
1150/* Helper to get a pointer to an object's __dict__ slot, if any */
1151
1152PyObject **
1153_PyObject_GetDictPtr(PyObject *obj)
1154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 Py_ssize_t dictoffset;
1156 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 dictoffset = tp->tp_dictoffset;
1159 if (dictoffset == 0)
1160 return NULL;
1161 if (dictoffset < 0) {
1162 Py_ssize_t tsize;
1163 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 tsize = ((PyVarObject *)obj)->ob_size;
1166 if (tsize < 0)
1167 tsize = -tsize;
1168 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001171 _PyObject_ASSERT(obj, dictoffset > 0);
1172 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 }
1174 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175}
1176
Tim Peters6d6c1a32001-08-02 04:15:00 +00001177PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001178PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 Py_INCREF(obj);
1181 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001182}
1183
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001184/* Helper used when the __next__ method is removed from a type:
1185 tp_iternext is never NULL and can be safely called without checking
1186 on every iteration.
1187 */
1188
1189PyObject *
1190_PyObject_NextNotImplemented(PyObject *self)
1191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyErr_Format(PyExc_TypeError,
1193 "'%.200s' object is not iterable",
1194 Py_TYPE(self)->tp_name);
1195 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001196}
1197
Yury Selivanovf2392132016-12-13 19:03:51 -05001198
1199/* Specialized version of _PyObject_GenericGetAttrWithDict
1200 specifically for the LOAD_METHOD opcode.
1201
1202 Return 1 if a method is found, 0 if it's a regular attribute
1203 from __dict__ or something returned by using a descriptor
1204 protocol.
1205
1206 `method` will point to the resolved attribute or NULL. In the
1207 latter case, an error will be set.
1208*/
1209int
1210_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1211{
1212 PyTypeObject *tp = Py_TYPE(obj);
1213 PyObject *descr;
1214 descrgetfunc f = NULL;
1215 PyObject **dictptr, *dict;
1216 PyObject *attr;
1217 int meth_found = 0;
1218
1219 assert(*method == NULL);
1220
1221 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1222 || !PyUnicode_Check(name)) {
1223 *method = PyObject_GetAttr(obj, name);
1224 return 0;
1225 }
1226
1227 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1228 return 0;
1229
1230 descr = _PyType_Lookup(tp, name);
1231 if (descr != NULL) {
1232 Py_INCREF(descr);
Jeroen Demeyereb65e242019-05-28 14:42:53 +02001233 if (PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001234 meth_found = 1;
1235 } else {
1236 f = descr->ob_type->tp_descr_get;
1237 if (f != NULL && PyDescr_IsData(descr)) {
1238 *method = f(descr, obj, (PyObject *)obj->ob_type);
1239 Py_DECREF(descr);
1240 return 0;
1241 }
1242 }
1243 }
1244
1245 dictptr = _PyObject_GetDictPtr(obj);
1246 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1247 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001248 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001249 if (attr != NULL) {
1250 Py_INCREF(attr);
1251 *method = attr;
1252 Py_DECREF(dict);
1253 Py_XDECREF(descr);
1254 return 0;
1255 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001256 else {
1257 Py_DECREF(dict);
1258 if (PyErr_Occurred()) {
1259 Py_XDECREF(descr);
1260 return 0;
1261 }
1262 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001263 }
1264
1265 if (meth_found) {
1266 *method = descr;
1267 return 1;
1268 }
1269
1270 if (f != NULL) {
1271 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1272 Py_DECREF(descr);
1273 return 0;
1274 }
1275
1276 if (descr != NULL) {
1277 *method = descr;
1278 return 0;
1279 }
1280
1281 PyErr_Format(PyExc_AttributeError,
1282 "'%.50s' object has no attribute '%U'",
1283 tp->tp_name, name);
1284 return 0;
1285}
1286
1287/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001288
Raymond Hettinger01538262003-03-17 08:24:35 +00001289PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001290_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1291 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292{
Yury Selivanovf2392132016-12-13 19:03:51 -05001293 /* Make sure the logic of _PyObject_GetMethod is in sync with
1294 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001295
1296 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001297 */
1298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 PyTypeObject *tp = Py_TYPE(obj);
1300 PyObject *descr = NULL;
1301 PyObject *res = NULL;
1302 descrgetfunc f;
1303 Py_ssize_t dictoffset;
1304 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (!PyUnicode_Check(name)){
1307 PyErr_Format(PyExc_TypeError,
1308 "attribute name must be string, not '%.200s'",
1309 name->ob_type->tp_name);
1310 return NULL;
1311 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001312 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (tp->tp_dict == NULL) {
1315 if (PyType_Ready(tp) < 0)
1316 goto done;
1317 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 f = NULL;
1322 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001323 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 f = descr->ob_type->tp_descr_get;
1325 if (f != NULL && PyDescr_IsData(descr)) {
1326 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001327 if (res == NULL && suppress &&
1328 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1329 PyErr_Clear();
1330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 goto done;
1332 }
1333 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001334
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001335 if (dict == NULL) {
1336 /* Inline _PyObject_GetDictPtr */
1337 dictoffset = tp->tp_dictoffset;
1338 if (dictoffset != 0) {
1339 if (dictoffset < 0) {
1340 Py_ssize_t tsize;
1341 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001342
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001343 tsize = ((PyVarObject *)obj)->ob_size;
1344 if (tsize < 0)
1345 tsize = -tsize;
1346 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001347 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001348
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001349 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001350 _PyObject_ASSERT(obj, dictoffset > 0);
1351 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001353 dictptr = (PyObject **) ((char *)obj + dictoffset);
1354 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 }
1356 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001357 if (dict != NULL) {
1358 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001359 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001360 if (res != NULL) {
1361 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001362 Py_DECREF(dict);
1363 goto done;
1364 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001365 else {
1366 Py_DECREF(dict);
1367 if (PyErr_Occurred()) {
1368 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1369 PyErr_Clear();
1370 }
1371 else {
1372 goto done;
1373 }
1374 }
1375 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001376 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (f != NULL) {
1379 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001380 if (res == NULL && suppress &&
1381 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1382 PyErr_Clear();
1383 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 goto done;
1385 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (descr != NULL) {
1388 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001389 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 goto done;
1391 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001392
INADA Naoki378edee2018-01-16 20:52:41 +09001393 if (!suppress) {
1394 PyErr_Format(PyExc_AttributeError,
1395 "'%.50s' object has no attribute '%U'",
1396 tp->tp_name, name);
1397 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001398 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001399 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 Py_DECREF(name);
1401 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001402}
1403
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001404PyObject *
1405PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1406{
INADA Naoki378edee2018-01-16 20:52:41 +09001407 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001408}
1409
Tim Peters6d6c1a32001-08-02 04:15:00 +00001410int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001411_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1412 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyTypeObject *tp = Py_TYPE(obj);
1415 PyObject *descr;
1416 descrsetfunc f;
1417 PyObject **dictptr;
1418 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 if (!PyUnicode_Check(name)){
1421 PyErr_Format(PyExc_TypeError,
1422 "attribute name must be string, not '%.200s'",
1423 name->ob_type->tp_name);
1424 return -1;
1425 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001426
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001427 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1428 return -1;
1429
1430 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001435 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001437 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 res = f(descr, obj, value);
1439 goto done;
1440 }
1441 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001442
Steve Dowerb82e17e2019-05-23 08:45:22 -07001443 /* XXX [Steve Dower] These are really noisy - worth it? */
1444 /*if (PyType_Check(obj) || PyModule_Check(obj)) {
1445 if (value && PySys_Audit("object.__setattr__", "OOO", obj, name, value) < 0)
1446 return -1;
1447 if (!value && PySys_Audit("object.__delattr__", "OO", obj, name) < 0)
1448 return -1;
1449 }*/
1450
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001451 if (dict == NULL) {
1452 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001453 if (dictptr == NULL) {
1454 if (descr == NULL) {
1455 PyErr_Format(PyExc_AttributeError,
1456 "'%.100s' object has no attribute '%U'",
1457 tp->tp_name, name);
1458 }
1459 else {
1460 PyErr_Format(PyExc_AttributeError,
1461 "'%.50s' object attribute '%U' is read-only",
1462 tp->tp_name, name);
1463 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001464 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001466 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001467 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001468 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001469 Py_INCREF(dict);
1470 if (value == NULL)
1471 res = PyDict_DelItem(dict, name);
1472 else
1473 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001474 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001476 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1477 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001479 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001480 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 Py_DECREF(name);
1482 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001483}
1484
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001485int
1486PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1487{
1488 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1489}
1490
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001491int
1492PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1493{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001494 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001495 if (dictptr == NULL) {
1496 PyErr_SetString(PyExc_AttributeError,
1497 "This object has no __dict__");
1498 return -1;
1499 }
1500 if (value == NULL) {
1501 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1502 return -1;
1503 }
1504 if (!PyDict_Check(value)) {
1505 PyErr_Format(PyExc_TypeError,
1506 "__dict__ must be set to a dictionary, "
1507 "not a '%.200s'", Py_TYPE(value)->tp_name);
1508 return -1;
1509 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001510 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001511 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001512 return 0;
1513}
1514
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001515
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001516/* Test a value used as condition, e.g., in a for or if statement.
1517 Return -1 if an error occurred */
1518
1519int
Fred Drake100814d2000-07-09 15:48:49 +00001520PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_ssize_t res;
1523 if (v == Py_True)
1524 return 1;
1525 if (v == Py_False)
1526 return 0;
1527 if (v == Py_None)
1528 return 0;
1529 else if (v->ob_type->tp_as_number != NULL &&
1530 v->ob_type->tp_as_number->nb_bool != NULL)
1531 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1532 else if (v->ob_type->tp_as_mapping != NULL &&
1533 v->ob_type->tp_as_mapping->mp_length != NULL)
1534 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1535 else if (v->ob_type->tp_as_sequence != NULL &&
1536 v->ob_type->tp_as_sequence->sq_length != NULL)
1537 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1538 else
1539 return 1;
1540 /* if it is negative, it should be either -1 or -2 */
1541 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001542}
1543
Tim Peters803526b2002-07-07 05:13:56 +00001544/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001545 Return -1 if an error occurred */
1546
1547int
Fred Drake100814d2000-07-09 15:48:49 +00001548PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 int res;
1551 res = PyObject_IsTrue(v);
1552 if (res < 0)
1553 return res;
1554 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001555}
1556
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001557/* Test whether an object can be called */
1558
1559int
Fred Drake100814d2000-07-09 15:48:49 +00001560PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (x == NULL)
1563 return 0;
1564 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001565}
1566
Tim Peters7eea37e2001-09-04 22:08:56 +00001567
Georg Brandle32b4222007-03-10 22:13:27 +00001568/* Helper for PyObject_Dir without arguments: returns the local scope. */
1569static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001570_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001573 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001574
Victor Stinner41bb43a2013-10-29 01:19:37 +01001575 locals = PyEval_GetLocals();
1576 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 names = PyMapping_Keys(locals);
1580 if (!names)
1581 return NULL;
1582 if (!PyList_Check(names)) {
1583 PyErr_Format(PyExc_TypeError,
1584 "dir(): expected keys() of locals to be a list, "
1585 "not '%.200s'", Py_TYPE(names)->tp_name);
1586 Py_DECREF(names);
1587 return NULL;
1588 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001589 if (PyList_Sort(names)) {
1590 Py_DECREF(names);
1591 return NULL;
1592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* the locals don't need to be DECREF'd */
1594 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001595}
1596
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001597/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001598static PyObject *
1599_dir_object(PyObject *obj)
1600{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001601 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001602 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001603
Victor Stinner24702042018-10-26 17:16:37 +02001604 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001606 if (!PyErr_Occurred())
1607 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1608 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001610 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001611 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001612 Py_DECREF(dirfunc);
1613 if (result == NULL)
1614 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001615 /* return sorted(result) */
1616 sorted = PySequence_List(result);
1617 Py_DECREF(result);
1618 if (sorted == NULL)
1619 return NULL;
1620 if (PyList_Sort(sorted)) {
1621 Py_DECREF(sorted);
1622 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001624 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001625}
1626
1627/* Implementation of dir() -- if obj is NULL, returns the names in the current
1628 (local) scope. Otherwise, performs introspection of the object: returns a
1629 sorted list of attribute names (supposedly) accessible from the object
1630*/
1631PyObject *
1632PyObject_Dir(PyObject *obj)
1633{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001634 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001635}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001636
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001637/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001638None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001639There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001640so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001641*/
1642
Guido van Rossum0c182a11992-03-27 17:26:13 +00001643/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001644static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001645none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001648}
1649
Barry Warsaw9bf16442001-01-23 16:24:35 +00001650/* ARGUSED */
1651static void
Tim Peters803526b2002-07-07 05:13:56 +00001652none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* This should never get called, but we also don't want to SEGV if
1655 * we accidentally decref None out of existence.
1656 */
1657 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001658}
1659
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001660static PyObject *
1661none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1662{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001663 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001664 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1665 return NULL;
1666 }
1667 Py_RETURN_NONE;
1668}
1669
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001670static int
1671none_bool(PyObject *v)
1672{
1673 return 0;
1674}
1675
1676static PyNumberMethods none_as_number = {
1677 0, /* nb_add */
1678 0, /* nb_subtract */
1679 0, /* nb_multiply */
1680 0, /* nb_remainder */
1681 0, /* nb_divmod */
1682 0, /* nb_power */
1683 0, /* nb_negative */
1684 0, /* nb_positive */
1685 0, /* nb_absolute */
1686 (inquiry)none_bool, /* nb_bool */
1687 0, /* nb_invert */
1688 0, /* nb_lshift */
1689 0, /* nb_rshift */
1690 0, /* nb_and */
1691 0, /* nb_xor */
1692 0, /* nb_or */
1693 0, /* nb_int */
1694 0, /* nb_reserved */
1695 0, /* nb_float */
1696 0, /* nb_inplace_add */
1697 0, /* nb_inplace_subtract */
1698 0, /* nb_inplace_multiply */
1699 0, /* nb_inplace_remainder */
1700 0, /* nb_inplace_power */
1701 0, /* nb_inplace_lshift */
1702 0, /* nb_inplace_rshift */
1703 0, /* nb_inplace_and */
1704 0, /* nb_inplace_xor */
1705 0, /* nb_inplace_or */
1706 0, /* nb_floor_divide */
1707 0, /* nb_true_divide */
1708 0, /* nb_inplace_floor_divide */
1709 0, /* nb_inplace_true_divide */
1710 0, /* nb_index */
1711};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001712
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001713PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1715 "NoneType",
1716 0,
1717 0,
1718 none_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001719 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 0, /*tp_getattr*/
1721 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001722 0, /*tp_as_async*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001724 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 0, /*tp_as_sequence*/
1726 0, /*tp_as_mapping*/
1727 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001728 0, /*tp_call */
1729 0, /*tp_str */
1730 0, /*tp_getattro */
1731 0, /*tp_setattro */
1732 0, /*tp_as_buffer */
1733 Py_TPFLAGS_DEFAULT, /*tp_flags */
1734 0, /*tp_doc */
1735 0, /*tp_traverse */
1736 0, /*tp_clear */
1737 0, /*tp_richcompare */
1738 0, /*tp_weaklistoffset */
1739 0, /*tp_iter */
1740 0, /*tp_iternext */
1741 0, /*tp_methods */
1742 0, /*tp_members */
1743 0, /*tp_getset */
1744 0, /*tp_base */
1745 0, /*tp_dict */
1746 0, /*tp_descr_get */
1747 0, /*tp_descr_set */
1748 0, /*tp_dictoffset */
1749 0, /*tp_init */
1750 0, /*tp_alloc */
1751 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001752};
1753
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001754PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001755 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001756 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001757};
1758
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001759/* NotImplemented is an object that can be used to signal that an
1760 operation is not implemented for the given type combination. */
1761
1762static PyObject *
1763NotImplemented_repr(PyObject *op)
1764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001766}
1767
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001768static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301769NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001770{
1771 return PyUnicode_FromString("NotImplemented");
1772}
1773
1774static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301775 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001776 {NULL, NULL}
1777};
1778
1779static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001780notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1781{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001782 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001783 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1784 return NULL;
1785 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001786 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001787}
1788
Armin Ronacher226b1db2012-10-06 14:28:58 +02001789static void
1790notimplemented_dealloc(PyObject* ignore)
1791{
1792 /* This should never get called, but we also don't want to SEGV if
1793 * we accidentally decref NotImplemented out of existence.
1794 */
1795 Py_FatalError("deallocating NotImplemented");
1796}
1797
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001798PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1800 "NotImplementedType",
1801 0,
1802 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001803 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001804 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 0, /*tp_getattr*/
1806 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001807 0, /*tp_as_async*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 NotImplemented_repr, /*tp_repr*/
1809 0, /*tp_as_number*/
1810 0, /*tp_as_sequence*/
1811 0, /*tp_as_mapping*/
1812 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001813 0, /*tp_call */
1814 0, /*tp_str */
1815 0, /*tp_getattro */
1816 0, /*tp_setattro */
1817 0, /*tp_as_buffer */
1818 Py_TPFLAGS_DEFAULT, /*tp_flags */
1819 0, /*tp_doc */
1820 0, /*tp_traverse */
1821 0, /*tp_clear */
1822 0, /*tp_richcompare */
1823 0, /*tp_weaklistoffset */
1824 0, /*tp_iter */
1825 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001826 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001827 0, /*tp_members */
1828 0, /*tp_getset */
1829 0, /*tp_base */
1830 0, /*tp_dict */
1831 0, /*tp_descr_get */
1832 0, /*tp_descr_set */
1833 0, /*tp_dictoffset */
1834 0, /*tp_init */
1835 0, /*tp_alloc */
1836 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001837};
1838
1839PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001841 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001842};
1843
Victor Stinner331a6a52019-05-27 16:39:22 +02001844PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01001845_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001846{
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001847#define INIT_TYPE(TYPE, NAME) \
1848 do { \
1849 if (PyType_Ready(TYPE) < 0) { \
Victor Stinner331a6a52019-05-27 16:39:22 +02001850 return _PyStatus_ERR("Can't initialize " NAME " type"); \
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001851 } \
1852 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001853
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001854 INIT_TYPE(&PyBaseObject_Type, "object");
1855 INIT_TYPE(&PyType_Type, "type");
1856 INIT_TYPE(&_PyWeakref_RefType, "weakref");
1857 INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
1858 INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
1859 INIT_TYPE(&PyLong_Type, "int");
1860 INIT_TYPE(&PyBool_Type, "bool");
1861 INIT_TYPE(&PyByteArray_Type, "bytearray");
1862 INIT_TYPE(&PyBytes_Type, "str");
1863 INIT_TYPE(&PyList_Type, "list");
1864 INIT_TYPE(&_PyNone_Type, "None");
1865 INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
1866 INIT_TYPE(&PyTraceBack_Type, "traceback");
1867 INIT_TYPE(&PySuper_Type, "super");
1868 INIT_TYPE(&PyRange_Type, "range");
1869 INIT_TYPE(&PyDict_Type, "dict");
1870 INIT_TYPE(&PyDictKeys_Type, "dict keys");
1871 INIT_TYPE(&PyDictValues_Type, "dict values");
1872 INIT_TYPE(&PyDictItems_Type, "dict items");
1873 INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
1874 INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
1875 INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
1876 INIT_TYPE(&PyODict_Type, "OrderedDict");
1877 INIT_TYPE(&PyODictKeys_Type, "odict_keys");
1878 INIT_TYPE(&PyODictItems_Type, "odict_items");
1879 INIT_TYPE(&PyODictValues_Type, "odict_values");
1880 INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
1881 INIT_TYPE(&PySet_Type, "set");
1882 INIT_TYPE(&PyUnicode_Type, "str");
1883 INIT_TYPE(&PySlice_Type, "slice");
1884 INIT_TYPE(&PyStaticMethod_Type, "static method");
1885 INIT_TYPE(&PyComplex_Type, "complex");
1886 INIT_TYPE(&PyFloat_Type, "float");
1887 INIT_TYPE(&PyFrozenSet_Type, "frozenset");
1888 INIT_TYPE(&PyProperty_Type, "property");
1889 INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
1890 INIT_TYPE(&PyMemoryView_Type, "memoryview");
1891 INIT_TYPE(&PyTuple_Type, "tuple");
1892 INIT_TYPE(&PyEnum_Type, "enumerate");
1893 INIT_TYPE(&PyReversed_Type, "reversed");
1894 INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
1895 INIT_TYPE(&PyCode_Type, "code");
1896 INIT_TYPE(&PyFrame_Type, "frame");
1897 INIT_TYPE(&PyCFunction_Type, "builtin function");
1898 INIT_TYPE(&PyMethod_Type, "method");
1899 INIT_TYPE(&PyFunction_Type, "function");
1900 INIT_TYPE(&PyDictProxy_Type, "dict proxy");
1901 INIT_TYPE(&PyGen_Type, "generator");
1902 INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
1903 INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
1904 INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
1905 INIT_TYPE(&PyEllipsis_Type, "ellipsis");
1906 INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
1907 INIT_TYPE(&_PyNamespace_Type, "namespace");
1908 INIT_TYPE(&PyCapsule_Type, "capsule");
1909 INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
1910 INIT_TYPE(&PyCell_Type, "cell");
1911 INIT_TYPE(&PyInstanceMethod_Type, "instance method");
1912 INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
1913 INIT_TYPE(&PyMethodDescr_Type, "method descr");
1914 INIT_TYPE(&PyCallIter_Type, "call iter");
1915 INIT_TYPE(&PySeqIter_Type, "sequence iterator");
Antoine Pitrou91f43802019-05-26 17:10:09 +02001916 INIT_TYPE(&PyPickleBuffer_Type, "pickle.PickleBuffer");
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001917 INIT_TYPE(&PyCoro_Type, "coroutine");
1918 INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
Eric Snowc11183c2019-03-15 16:35:46 -06001919 INIT_TYPE(&_PyInterpreterID_Type, "interpreter ID");
Victor Stinner331a6a52019-05-27 16:39:22 +02001920 return _PyStatus_OK();
Guido van Rossumba21a492001-08-16 08:17:26 +00001921
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001922#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001923}
1924
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001925
Guido van Rossum84a90321996-05-22 16:34:47 +00001926#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001927
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001928void
Fred Drake100814d2000-07-09 15:48:49 +00001929_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001930{
Victor Stinner9e00e802018-10-25 13:31:16 +02001931 if (_Py_tracemalloc_config.tracing) {
1932 _PyTraceMalloc_NewReference(op);
1933 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 _Py_INC_REFTOTAL;
1935 op->ob_refcnt = 1;
1936 _Py_AddToAllObjects(op, 1);
1937 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001938}
1939
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001940void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001941_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001942{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001943#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001944 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001945#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 if (op->ob_refcnt < 0)
1947 Py_FatalError("UNREF negative refcnt");
1948 if (op == &refchain ||
1949 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1950 fprintf(stderr, "* ob\n");
1951 _PyObject_Dump(op);
1952 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1953 _PyObject_Dump(op->_ob_prev->_ob_next);
1954 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1955 _PyObject_Dump(op->_ob_next->_ob_prev);
1956 Py_FatalError("UNREF invalid object");
1957 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001958#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1960 if (p == op)
1961 break;
1962 }
1963 if (p == &refchain) /* Not found */
1964 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001965#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 op->_ob_next->_ob_prev = op->_ob_prev;
1967 op->_ob_prev->_ob_next = op->_ob_next;
1968 op->_ob_next = op->_ob_prev = NULL;
1969 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001970}
1971
Tim Peters269b2a62003-04-17 19:52:29 +00001972/* Print all live objects. Because PyObject_Print is called, the
1973 * interpreter must be in a healthy state.
1974 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001975void
Fred Drake100814d2000-07-09 15:48:49 +00001976_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 PyObject *op;
1979 fprintf(fp, "Remaining objects:\n");
1980 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001981 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", (void *)op, op->ob_refcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 if (PyObject_Print(op, fp, 0) != 0)
1983 PyErr_Clear();
1984 putc('\n', fp);
1985 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001986}
1987
Tim Peters269b2a62003-04-17 19:52:29 +00001988/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1989 * doesn't make any calls to the Python C API, so is always safe to call.
1990 */
1991void
1992_Py_PrintReferenceAddresses(FILE *fp)
1993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 PyObject *op;
1995 fprintf(fp, "Remaining object addresses:\n");
1996 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001997 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", (void *)op,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001999}
2000
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002001PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002002_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 int i, n;
2005 PyObject *t = NULL;
2006 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2009 return NULL;
2010 op = refchain._ob_next;
2011 res = PyList_New(0);
2012 if (res == NULL)
2013 return NULL;
2014 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2015 while (op == self || op == args || op == res || op == t ||
2016 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2017 op = op->_ob_next;
2018 if (op == &refchain)
2019 return res;
2020 }
2021 if (PyList_Append(res, op) < 0) {
2022 Py_DECREF(res);
2023 return NULL;
2024 }
2025 op = op->_ob_next;
2026 }
2027 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002028}
2029
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002030#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002031
Benjamin Petersonb173f782009-05-05 22:31:58 +00002032
Guido van Rossum84a90321996-05-22 16:34:47 +00002033/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002034Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002035
2036
David Malcolm49526f42012-06-22 14:55:41 -04002037void
2038_PyObject_DebugTypeStats(FILE *out)
2039{
David Malcolm49526f42012-06-22 14:55:41 -04002040 _PyDict_DebugMallocStats(out);
2041 _PyFloat_DebugMallocStats(out);
2042 _PyFrame_DebugMallocStats(out);
2043 _PyList_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04002044 _PyTuple_DebugMallocStats(out);
2045}
Guido van Rossumb18618d2000-05-03 23:44:39 +00002046
Guido van Rossum86610361998-04-10 22:32:46 +00002047/* These methods are used to control infinite recursion in repr, str, print,
2048 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00002049 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00002050 Py_ReprLeave() to avoid infinite recursion.
2051
2052 Py_ReprEnter() returns 0 the first time it is called for a particular
2053 object and 1 every time thereafter. It returns -1 if an exception
2054 occurred. Py_ReprLeave() has no return value.
2055
2056 See dictobject.c and listobject.c for examples of use.
2057*/
2058
Guido van Rossum86610361998-04-10 22:32:46 +00002059int
Fred Drake100814d2000-07-09 15:48:49 +00002060Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 PyObject *dict;
2063 PyObject *list;
2064 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02002067 /* Ignore a missing thread-state, so that this function can be called
2068 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (dict == NULL)
2070 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002071 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002073 if (PyErr_Occurred()) {
2074 return -1;
2075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 list = PyList_New(0);
2077 if (list == NULL)
2078 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01002079 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 return -1;
2081 Py_DECREF(list);
2082 }
2083 i = PyList_GET_SIZE(list);
2084 while (--i >= 0) {
2085 if (PyList_GET_ITEM(list, i) == obj)
2086 return 1;
2087 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002088 if (PyList_Append(list, obj) < 0)
2089 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002091}
2092
2093void
Fred Drake100814d2000-07-09 15:48:49 +00002094Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyObject *dict;
2097 PyObject *list;
2098 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002099 PyObject *error_type, *error_value, *error_traceback;
2100
2101 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 dict = PyThreadState_GetDict();
2104 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002105 goto finally;
2106
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002107 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002109 goto finally;
2110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 i = PyList_GET_SIZE(list);
2112 /* Count backwards because we always expect obj to be list[-1] */
2113 while (--i >= 0) {
2114 if (PyList_GET_ITEM(list, i) == obj) {
2115 PyList_SetSlice(list, i, i + 1, NULL);
2116 break;
2117 }
2118 }
Victor Stinner1b634932013-07-16 22:24:44 +02002119
2120finally:
2121 /* ignore exceptions because there is no way to report them. */
2122 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002123}
Guido van Rossumd724b232000-03-13 16:01:29 +00002124
Tim Peters803526b2002-07-07 05:13:56 +00002125/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002126
Tim Peters803526b2002-07-07 05:13:56 +00002127/* Add op to the _PyTrash_delete_later list. Called when the current
2128 * call-stack depth gets large. op must be a currently untracked gc'ed
2129 * object, with refcount 0. Py_DECREF must already have been called on it.
2130 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002131void
Fred Drake100814d2000-07-09 15:48:49 +00002132_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002133{
Victor Stinner24702042018-10-26 17:16:37 +02002134 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2135 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2136 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002137 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002138 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002139}
2140
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002141/* The equivalent API, using per-thread state recursion info */
2142void
2143_PyTrash_thread_deposit_object(PyObject *op)
2144{
Victor Stinner50b48572018-11-01 01:51:40 +01002145 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002146 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2147 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2148 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002149 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002150 tstate->trash_delete_later = op;
2151}
2152
Min ho Kimc4cacc82019-07-31 08:16:13 +10002153/* Deallocate all the objects in the _PyTrash_delete_later list. Called when
Tim Peters803526b2002-07-07 05:13:56 +00002154 * the call-stack unwinds again.
2155 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002156void
Fred Drake100814d2000-07-09 15:48:49 +00002157_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002158{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002159 while (_PyRuntime.gc.trash_delete_later) {
2160 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002162
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002163 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002164 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* Call the deallocator directly. This used to try to
2167 * fool Py_DECREF into calling it indirectly, but
2168 * Py_DECREF was already called on this object, and in
2169 * assorted non-release builds calling Py_DECREF again ends
2170 * up distorting allocation statistics.
2171 */
Victor Stinner24702042018-10-26 17:16:37 +02002172 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002173 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002175 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002177}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002178
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002179/* The equivalent API, using per-thread state recursion info */
2180void
2181_PyTrash_thread_destroy_chain(void)
2182{
Victor Stinner50b48572018-11-01 01:51:40 +01002183 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002184 /* We need to increase trash_delete_nesting here, otherwise,
2185 _PyTrash_thread_destroy_chain will be called recursively
2186 and then possibly crash. An example that may crash without
2187 increase:
2188 N = 500000 # need to be large enough
2189 ob = object()
2190 tups = [(ob,) for i in range(N)]
2191 for i in range(49):
2192 tups = [(tup,) for tup in tups]
2193 del tups
2194 */
2195 assert(tstate->trash_delete_nesting == 0);
2196 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002197 while (tstate->trash_delete_later) {
2198 PyObject *op = tstate->trash_delete_later;
2199 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2200
2201 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002202 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002203
2204 /* Call the deallocator directly. This used to try to
2205 * fool Py_DECREF into calling it indirectly, but
2206 * Py_DECREF was already called on this object, and in
2207 * assorted non-release builds calling Py_DECREF again ends
2208 * up distorting allocation statistics.
2209 */
Victor Stinner24702042018-10-26 17:16:37 +02002210 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002211 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002212 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002213 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002214 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002215}
2216
Victor Stinner626bff82018-10-25 17:31:10 +02002217
2218void
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002219_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002220 const char *file, int line, const char *function)
2221{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002222 fprintf(stderr, "%s:%d: ", file, line);
2223 if (function) {
2224 fprintf(stderr, "%s: ", function);
2225 }
Victor Stinner626bff82018-10-25 17:31:10 +02002226 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002227
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002228 if (expr) {
2229 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002230 }
2231 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002232 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002233 }
2234 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002235
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002236 if (msg) {
2237 fprintf(stderr, ": %s", msg);
2238 }
2239 fprintf(stderr, "\n");
2240 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002241
Victor Stinner68762572019-10-07 18:42:01 +02002242 if (_PyObject_IsFreed(obj)) {
Victor Stinner626bff82018-10-25 17:31:10 +02002243 /* It seems like the object memory has been freed:
2244 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +02002245 fprintf(stderr, "<object at %p is freed>\n", obj);
Victor Stinner68762572019-10-07 18:42:01 +02002246 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002247 }
2248 else {
penguindustin96466302019-05-06 14:57:17 -04002249 /* Display the traceback where the object has been allocated.
Victor Stinner626bff82018-10-25 17:31:10 +02002250 Do it before dumping repr(obj), since repr() is more likely
2251 to crash than dumping the traceback. */
2252 void *ptr;
2253 PyTypeObject *type = Py_TYPE(obj);
2254 if (PyType_IS_GC(type)) {
2255 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2256 }
2257 else {
2258 ptr = (void *)obj;
2259 }
2260 _PyMem_DumpTraceback(fileno(stderr), ptr);
2261
2262 /* This might succeed or fail, but we're about to abort, so at least
2263 try to provide any extra info we can: */
2264 _PyObject_Dump(obj);
Victor Stinner77753492019-10-07 23:44:05 +02002265
2266 fprintf(stderr, "\n");
2267 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002268 }
Victor Stinner626bff82018-10-25 17:31:10 +02002269
2270 Py_FatalError("_PyObject_AssertFailed");
2271}
2272
Victor Stinner3c09dca2018-10-30 14:48:26 +01002273
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002274#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002275
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002276void
2277_Py_Dealloc(PyObject *op)
2278{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002279 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2280#ifdef Py_TRACE_REFS
2281 _Py_ForgetReference(op);
2282#else
2283 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002284#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002285 (*dealloc)(op);
2286}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002287
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002288#ifdef __cplusplus
2289}
2290#endif