blob: 67a6386e2a51d8563483fc6ae15ca362808acf46 [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 Stinner7a1f6c22020-01-30 09:02:14 +01009#include "pycore_pylifecycle.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010010#include "pycore_pystate.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +000011#include "frameobject.h"
Eric Snowc11183c2019-03-15 16:35:46 -060012#include "interpreteridobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014#ifdef __cplusplus
15extern "C" {
16#endif
17
Victor Stinner626bff82018-10-25 17:31:10 +020018/* Defined in tracemalloc.c */
19extern void _PyMem_DumpTraceback(int fd, const void *ptr);
20
Victor Stinnerbd303c12013-11-07 23:07:29 +010021_Py_IDENTIFIER(Py_Repr);
22_Py_IDENTIFIER(__bytes__);
23_Py_IDENTIFIER(__dir__);
24_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010025
Victor Stinner0fc91ee2019-04-12 21:51:34 +020026
27int
28_PyObject_CheckConsistency(PyObject *op, int check_content)
29{
Victor Stinner68762572019-10-07 18:42:01 +020030#define CHECK(expr) \
31 do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
Victor Stinner0fc91ee2019-04-12 21:51:34 +020032
Victor Stinner68762572019-10-07 18:42:01 +020033 CHECK(!_PyObject_IsFreed(op));
34 CHECK(Py_REFCNT(op) >= 1);
35
36 CHECK(op->ob_type != NULL);
37 _PyType_CheckConsistency(op->ob_type);
Victor Stinner0fc91ee2019-04-12 21:51:34 +020038
39 if (PyUnicode_Check(op)) {
40 _PyUnicode_CheckConsistency(op, check_content);
41 }
42 else if (PyDict_Check(op)) {
43 _PyDict_CheckConsistency(op, check_content);
44 }
45 return 1;
Victor Stinner68762572019-10-07 18:42:01 +020046
47#undef CHECK
Victor Stinner0fc91ee2019-04-12 21:51:34 +020048}
49
50
Tim Peters34592512002-07-11 06:23:50 +000051#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000052Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053
54Py_ssize_t
55_Py_GetRefTotal(void)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 PyObject *o;
58 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020059 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 if (o != NULL)
61 total -= o->ob_refcnt;
62 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063}
Nick Coghland6009512014-11-20 21:39:37 +100064
65void
66_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070067 fprintf(stderr,
68 "[%" PY_FORMAT_SIZE_T "d refs, "
69 "%" PY_FORMAT_SIZE_T "d blocks]\n",
70 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100071}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000072#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073
Guido van Rossum3f5da241990-12-20 15:06:42 +000074/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
75 These are used by the individual routines for object creation.
76 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077
Tim Peters78be7992003-03-23 02:51:01 +000078#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000079/* Head of circular doubly-linked list of all objects. These are linked
80 * together via the _ob_prev and _ob_next members of a PyObject, which
81 * exist only in a Py_TRACE_REFS build.
82 */
Tim Peters78be7992003-03-23 02:51:01 +000083static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000084
Tim Peters7571a0f2003-03-23 17:52:28 +000085/* Insert op at the front of the list of all objects. If force is true,
86 * op is added even if _ob_prev and _ob_next are non-NULL already. If
87 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
88 * force should be true if and only if op points to freshly allocated,
89 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000090 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000091 * Note that objects are normally added to the list via _Py_NewReference,
92 * which is called by PyObject_Init. Not all objects are initialized that
93 * way, though; exceptions include statically allocated type objects, and
94 * statically allocated singletons (like Py_True and Py_None).
95 */
Tim Peters36eb4df2003-03-23 03:33:13 +000096void
Tim Peters7571a0f2003-03-23 17:52:28 +000097_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000098{
Tim Peters7571a0f2003-03-23 17:52:28 +000099#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (!force) {
101 /* If it's initialized memory, op must be in or out of
102 * the list unambiguously.
103 */
Victor Stinner24702042018-10-26 17:16:37 +0200104 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Tim Peters78be7992003-03-23 02:51:01 +0000106#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 if (force || op->_ob_prev == NULL) {
108 op->_ob_next = refchain._ob_next;
109 op->_ob_prev = &refchain;
110 refchain._ob_next->_ob_prev = op;
111 refchain._ob_next = op;
112 }
Tim Peters7571a0f2003-03-23 17:52:28 +0000113}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +0000115
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000116#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000118/* All types are added to type_list, at least when
119 they get one object created. That makes them
120 immortal, which unfortunately contributes to
121 garbage itself. If unlist_types_without_objects
122 is set, they will be removed from the type_list
123 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +0000124static int unlist_types_without_objects;
Pablo Galindo49c75a82018-10-28 15:02:17 +0000125extern Py_ssize_t _Py_tuple_zero_allocs, _Py_fast_tuple_allocs;
126extern Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
127extern Py_ssize_t _Py_null_strings, _Py_one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000128void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000129_Py_dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000130{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200131 PyInterpreterState *interp = _PyInterpreterState_Get();
Victor Stinner331a6a52019-05-27 16:39:22 +0200132 if (!interp->config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300133 return;
Victor Stinner25420fe2017-11-20 18:12:22 -0800134 }
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000135
Eddie Elizondo745dc652018-02-21 20:55:18 -0800136 PyTypeObject *tp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 for (tp = type_list; tp; tp = tp->tp_next)
138 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
139 "freed: %" PY_FORMAT_SIZE_T "d, "
140 "max in use: %" PY_FORMAT_SIZE_T "d\n",
141 tp->tp_name, tp->tp_allocs, tp->tp_frees,
142 tp->tp_maxalloc);
143 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
144 "empty: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000145 _Py_fast_tuple_allocs, _Py_tuple_zero_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
147 "neg: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000148 _Py_quick_int_allocs, _Py_quick_neg_int_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
150 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000151 _Py_null_strings, _Py_one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000152}
153
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000154PyObject *
Pablo Galindo49c75a82018-10-28 15:02:17 +0000155_Py_get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyTypeObject *tp;
158 PyObject *result;
159 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 result = PyList_New(0);
162 if (result == NULL)
163 return NULL;
164 for (tp = type_list; tp; tp = tp->tp_next) {
165 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
166 tp->tp_frees, tp->tp_maxalloc);
167 if (v == NULL) {
168 Py_DECREF(result);
169 return NULL;
170 }
171 if (PyList_Append(result, v) < 0) {
172 Py_DECREF(v);
173 Py_DECREF(result);
174 return NULL;
175 }
176 Py_DECREF(v);
177 }
178 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000179}
180
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000181void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000182_Py_inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
185 /* first time; insert in linked list */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (type_list)
187 type_list->tp_prev = tp;
188 tp->tp_next = type_list;
189 /* Note that as of Python 2.2, heap-allocated type objects
190 * can go away, but this code requires that they stay alive
191 * until program exit. That's why we're careful with
192 * refcounts here. type_list gets a new reference to tp,
193 * while ownership of the reference type_list used to hold
194 * (if any) was transferred to tp->tp_next in the line above.
195 * tp is thus effectively immortal after this.
196 */
197 Py_INCREF(tp);
198 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000199#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 /* Also insert in the doubly-linked list of all objects,
201 * if not already there.
202 */
203 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000204#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 }
206 tp->tp_allocs++;
207 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
208 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000209}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210
Pablo Galindo49c75a82018-10-28 15:02:17 +0000211void _Py_dec_count(PyTypeObject *tp)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 tp->tp_frees++;
214 if (unlist_types_without_objects &&
215 tp->tp_allocs == tp->tp_frees) {
216 /* unlink the type from type_list */
217 if (tp->tp_prev)
218 tp->tp_prev->tp_next = tp->tp_next;
219 else
220 type_list = tp->tp_next;
221 if (tp->tp_next)
222 tp->tp_next->tp_prev = tp->tp_prev;
223 tp->tp_next = tp->tp_prev = NULL;
224 Py_DECREF(tp);
225 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000226}
227
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000228#endif
229
Tim Peters7c321a82002-07-09 02:57:01 +0000230#ifdef Py_REF_DEBUG
231/* Log a fatal error; doesn't return. */
232void
Victor Stinner18618e652018-10-25 17:28:11 +0200233_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000234{
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100235 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200236 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000237}
238
239#endif /* Py_REF_DEBUG */
240
Thomas Heller1328b522004-04-22 17:23:49 +0000241void
242Py_IncRef(PyObject *o)
243{
244 Py_XINCREF(o);
245}
246
247void
248Py_DecRef(PyObject *o)
249{
250 Py_XDECREF(o);
251}
252
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000253PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000254PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 if (op == NULL)
257 return PyErr_NoMemory();
258 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
259 Py_TYPE(op) = tp;
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400260 if (PyType_GetFlags(tp) & Py_TPFLAGS_HEAPTYPE) {
261 Py_INCREF(tp);
262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 _Py_NewReference(op);
264 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000265}
266
Guido van Rossumb18618d2000-05-03 23:44:39 +0000267PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000268PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 if (op == NULL)
271 return (PyVarObject *) PyErr_NoMemory();
272 /* Any changes should be reflected in PyObject_INIT_VAR */
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400273 Py_SIZE(op) = size;
274 PyObject_Init((PyObject *)op, tp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000276}
277
278PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000279_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *op;
282 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
283 if (op == NULL)
284 return PyErr_NoMemory();
285 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000286}
287
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000288PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000289_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 PyVarObject *op;
292 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
293 op = (PyVarObject *) PyObject_MALLOC(size);
294 if (op == NULL)
295 return (PyVarObject *)PyErr_NoMemory();
296 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000297}
298
Antoine Pitrou796564c2013-07-30 19:59:21 +0200299void
300PyObject_CallFinalizer(PyObject *self)
301{
302 PyTypeObject *tp = Py_TYPE(self);
303
Antoine Pitrouada319b2019-05-29 22:12:38 +0200304 if (tp->tp_finalize == NULL)
Antoine Pitrou796564c2013-07-30 19:59:21 +0200305 return;
306 /* tp_finalize should only be called once. */
307 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
308 return;
309
310 tp->tp_finalize(self);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900311 if (PyType_IS_GC(tp)) {
312 _PyGC_SET_FINALIZED(self);
313 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200314}
315
316int
317PyObject_CallFinalizerFromDealloc(PyObject *self)
318{
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100319 if (self->ob_refcnt != 0) {
320 _PyObject_ASSERT_FAILED_MSG(self,
321 "PyObject_CallFinalizerFromDealloc called "
322 "on object with a non-zero refcount");
323 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200324
325 /* Temporarily resurrect the object. */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200326 self->ob_refcnt = 1;
327
328 PyObject_CallFinalizer(self);
329
Victor Stinner24702042018-10-26 17:16:37 +0200330 _PyObject_ASSERT_WITH_MSG(self,
331 self->ob_refcnt > 0,
332 "refcount is too small");
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100333
334 /* Undo the temporary resurrection; can't use DECREF here, it would
335 * cause a recursive call. */
336 if (--self->ob_refcnt == 0) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200337 return 0; /* this is the normal path out */
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100338 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200339
340 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100341 * never happened. */
342 Py_ssize_t refcnt = self->ob_refcnt;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200343 _Py_NewReference(self);
344 self->ob_refcnt = refcnt;
345
Victor Stinner24702042018-10-26 17:16:37 +0200346 _PyObject_ASSERT(self,
347 (!PyType_IS_GC(Py_TYPE(self))
348 || _PyObject_GC_IS_TRACKED(self)));
Antoine Pitrou796564c2013-07-30 19:59:21 +0200349 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
350 * we need to undo that. */
351 _Py_DEC_REFTOTAL;
352 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
353 * chain, so no more to do there.
354 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
355 * _Py_NewReference bumped tp_allocs: both of those need to be
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100356 * undone. */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200357#ifdef COUNT_ALLOCS
358 --Py_TYPE(self)->tp_frees;
359 --Py_TYPE(self)->tp_allocs;
360#endif
361 return -1;
362}
363
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000364int
365PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (PyErr_CheckSignals())
369 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000370#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (PyOS_CheckStack()) {
372 PyErr_SetString(PyExc_MemoryError, "stack overflow");
373 return -1;
374 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000375#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 clearerr(fp); /* Clear any previous error condition */
377 if (op == NULL) {
378 Py_BEGIN_ALLOW_THREADS
379 fprintf(fp, "<nil>");
380 Py_END_ALLOW_THREADS
381 }
382 else {
Victor Stinner3ec9af72018-10-26 02:12:34 +0200383 if (op->ob_refcnt <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 /* XXX(twouters) cast refcount to long until %zd is
385 universally available */
386 Py_BEGIN_ALLOW_THREADS
387 fprintf(fp, "<refcnt %ld at %p>",
Zackery Spytz1a2252e2019-05-06 10:56:51 -0600388 (long)op->ob_refcnt, (void *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200390 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 else {
392 PyObject *s;
393 if (flags & Py_PRINT_RAW)
394 s = PyObject_Str(op);
395 else
396 s = PyObject_Repr(op);
397 if (s == NULL)
398 ret = -1;
399 else if (PyBytes_Check(s)) {
400 fwrite(PyBytes_AS_STRING(s), 1,
401 PyBytes_GET_SIZE(s), fp);
402 }
403 else if (PyUnicode_Check(s)) {
404 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200405 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600406 if (t == NULL) {
407 ret = -1;
408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 else {
410 fwrite(PyBytes_AS_STRING(t), 1,
411 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000412 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 }
414 }
415 else {
416 PyErr_Format(PyExc_TypeError,
417 "str() or repr() returned '%.100s'",
418 s->ob_type->tp_name);
419 ret = -1;
420 }
421 Py_XDECREF(s);
422 }
423 }
424 if (ret == 0) {
425 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300426 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 clearerr(fp);
428 ret = -1;
429 }
430 }
431 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000432}
433
Guido van Rossum38938152006-08-21 23:36:26 +0000434/* For debugging convenience. Set a breakpoint here and call it from your DLL */
435void
Thomas Woutersb2137042007-02-01 18:02:27 +0000436_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000437{
438}
439
Neal Norwitz1a997502003-01-13 20:13:12 +0000440
Victor Stinner4c409be2019-04-11 13:01:15 +0200441/* Heuristic checking if the object memory is uninitialized or deallocated.
442 Rely on the debug hooks on Python memory allocators:
443 see _PyMem_IsPtrFreed().
Victor Stinner82af0b62018-10-23 17:39:40 +0200444
445 The function can be used to prevent segmentation fault on dereferencing
Victor Stinner4c409be2019-04-11 13:01:15 +0200446 pointers like 0xDDDDDDDDDDDDDDDD. */
Victor Stinner82af0b62018-10-23 17:39:40 +0200447int
448_PyObject_IsFreed(PyObject *op)
449{
Victor Stinner2b00db62019-04-11 11:33:27 +0200450 if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(op->ob_type)) {
Victor Stinner2cf5d322018-11-22 16:32:57 +0100451 return 1;
452 }
Victor Stinner2b00db62019-04-11 11:33:27 +0200453 /* ignore op->ob_ref: its value can have be modified
Victor Stinner82af0b62018-10-23 17:39:40 +0200454 by Py_INCREF() and Py_DECREF(). */
455#ifdef Py_TRACE_REFS
Pablo Galindo36e33c32019-10-08 00:43:14 +0100456 if (op->_ob_next != NULL && _PyMem_IsPtrFreed(op->_ob_next)) {
Victor Stinner2b00db62019-04-11 11:33:27 +0200457 return 1;
458 }
Pablo Galindo36e33c32019-10-08 00:43:14 +0100459 if (op->_ob_prev != NULL && _PyMem_IsPtrFreed(op->_ob_prev)) {
460 return 1;
461 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200462#endif
Victor Stinner2b00db62019-04-11 11:33:27 +0200463 return 0;
Victor Stinner82af0b62018-10-23 17:39:40 +0200464}
465
466
Barry Warsaw9bf16442001-01-23 16:24:35 +0000467/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000468void
469_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000470{
Victor Stinner82af0b62018-10-23 17:39:40 +0200471 if (_PyObject_IsFreed(op)) {
472 /* It seems like the object memory has been freed:
473 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +0200474 fprintf(stderr, "<object at %p is freed>\n", op);
Victor Stinner68762572019-10-07 18:42:01 +0200475 fflush(stderr);
Victor Stinner2cf5d322018-11-22 16:32:57 +0100476 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200477 }
478
Victor Stinner68762572019-10-07 18:42:01 +0200479 /* first, write fields which are the least likely to crash */
480 fprintf(stderr, "object address : %p\n", (void *)op);
Victor Stinner82af0b62018-10-23 17:39:40 +0200481 /* XXX(twouters) cast refcount to long until %zd is
482 universally available */
Victor Stinner68762572019-10-07 18:42:01 +0200483 fprintf(stderr, "object refcount : %ld\n", (long)op->ob_refcnt);
484 fflush(stderr);
485
486 PyTypeObject *type = Py_TYPE(op);
487 fprintf(stderr, "object type : %p\n", type);
488 fprintf(stderr, "object type name: %s\n",
489 type==NULL ? "NULL" : type->tp_name);
490
491 /* the most dangerous part */
492 fprintf(stderr, "object repr : ");
493 fflush(stderr);
494
495 PyGILState_STATE gil = PyGILState_Ensure();
496 PyObject *error_type, *error_value, *error_traceback;
497 PyErr_Fetch(&error_type, &error_value, &error_traceback);
498
499 (void)PyObject_Print(op, stderr, 0);
500 fflush(stderr);
501
502 PyErr_Restore(error_type, error_value, error_traceback);
503 PyGILState_Release(gil);
504
505 fprintf(stderr, "\n");
Victor Stinner82af0b62018-10-23 17:39:40 +0200506 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000507}
Barry Warsaw903138f2001-01-23 16:33:18 +0000508
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000510PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyObject *res;
513 if (PyErr_CheckSignals())
514 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000515#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (PyOS_CheckStack()) {
517 PyErr_SetString(PyExc_MemoryError, "stack overflow");
518 return NULL;
519 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000520#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (v == NULL)
522 return PyUnicode_FromString("<NULL>");
523 if (Py_TYPE(v)->tp_repr == NULL)
524 return PyUnicode_FromFormat("<%s object at %p>",
525 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200526
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100527 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner33824f62013-08-26 14:05:19 +0200528#ifdef Py_DEBUG
529 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100530 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000531 caller loses its exception */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100532 assert(!_PyErr_Occurred(tstate));
Victor Stinner33824f62013-08-26 14:05:19 +0200533#endif
534
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200535 /* It is possible for a type to have a tp_repr representation that loops
536 infinitely. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100537 if (_Py_EnterRecursiveCall(tstate,
538 " while getting the repr of an object")) {
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200539 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 res = (*v->ob_type->tp_repr)(v);
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100542 _Py_LeaveRecursiveCall(tstate);
543
544 if (res == NULL) {
Victor Stinner0a54cf12011-12-01 03:22:44 +0100545 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100546 }
Victor Stinner0a54cf12011-12-01 03:22:44 +0100547 if (!PyUnicode_Check(res)) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100548 _PyErr_Format(tstate, PyExc_TypeError,
549 "__repr__ returned non-string (type %.200s)",
550 res->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 Py_DECREF(res);
552 return NULL;
553 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100554#ifndef Py_DEBUG
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100555 if (PyUnicode_READY(res) < 0) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100556 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100557 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100558#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000563PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 PyObject *res;
566 if (PyErr_CheckSignals())
567 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000568#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (PyOS_CheckStack()) {
570 PyErr_SetString(PyExc_MemoryError, "stack overflow");
571 return NULL;
572 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000573#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (v == NULL)
575 return PyUnicode_FromString("<NULL>");
576 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100577#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100578 if (PyUnicode_READY(v) < 0)
579 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100580#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 Py_INCREF(v);
582 return v;
583 }
584 if (Py_TYPE(v)->tp_str == NULL)
585 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000586
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100587 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner33824f62013-08-26 14:05:19 +0200588#ifdef Py_DEBUG
589 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100590 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000591 caller loses its exception */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100592 assert(!_PyErr_Occurred(tstate));
Victor Stinner33824f62013-08-26 14:05:19 +0200593#endif
594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 /* It is possible for a type to have a tp_str representation that loops
596 infinitely. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100597 if (_Py_EnterRecursiveCall(tstate, " while getting the str of an object")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 res = (*Py_TYPE(v)->tp_str)(v);
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100601 _Py_LeaveRecursiveCall(tstate);
602
603 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100605 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (!PyUnicode_Check(res)) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100607 _PyErr_Format(tstate, PyExc_TypeError,
608 "__str__ returned non-string (type %.200s)",
609 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 Py_DECREF(res);
611 return NULL;
612 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100613#ifndef Py_DEBUG
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100614 if (PyUnicode_READY(res) < 0) {
Victor Stinner4ead7c72011-11-20 19:48:36 +0100615 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100616 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100617#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100618 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000620}
621
Georg Brandl559e5d72008-06-11 18:37:52 +0000622PyObject *
623PyObject_ASCII(PyObject *v)
624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 repr = PyObject_Repr(v);
628 if (repr == NULL)
629 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000630
Victor Stinneraf037572013-04-14 18:44:10 +0200631 if (PyUnicode_IS_ASCII(repr))
632 return repr;
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200635 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_DECREF(repr);
637 if (ascii == NULL)
638 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 res = PyUnicode_DecodeASCII(
641 PyBytes_AS_STRING(ascii),
642 PyBytes_GET_SIZE(ascii),
643 NULL);
644
645 Py_DECREF(ascii);
646 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000647}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000648
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000649PyObject *
650PyObject_Bytes(PyObject *v)
651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (v == NULL)
655 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 if (PyBytes_CheckExact(v)) {
658 Py_INCREF(v);
659 return v;
660 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000661
Benjamin Petersonce798522012-01-22 11:24:29 -0500662 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100664 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 Py_DECREF(func);
666 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000667 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000669 PyErr_Format(PyExc_TypeError,
670 "__bytes__ returned non-bytes (type %.200s)",
671 Py_TYPE(result)->tp_name);
672 Py_DECREF(result);
673 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 }
675 return result;
676 }
677 else if (PyErr_Occurred())
678 return NULL;
679 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000680}
681
Jeroen Demeyerbf17d412019-11-05 16:48:04 +0100682
683/*
684def _PyObject_FunctionStr(x):
685 try:
686 qualname = x.__qualname__
687 except AttributeError:
688 return str(x)
689 try:
690 mod = x.__module__
691 if mod is not None and mod != 'builtins':
692 return f"{x.__module__}.{qualname}()"
693 except AttributeError:
694 pass
695 return qualname
696*/
697PyObject *
698_PyObject_FunctionStr(PyObject *x)
699{
700 _Py_IDENTIFIER(__module__);
701 _Py_IDENTIFIER(__qualname__);
702 _Py_IDENTIFIER(builtins);
703 assert(!PyErr_Occurred());
704 PyObject *qualname;
705 int ret = _PyObject_LookupAttrId(x, &PyId___qualname__, &qualname);
706 if (qualname == NULL) {
707 if (ret < 0) {
708 return NULL;
709 }
710 return PyObject_Str(x);
711 }
712 PyObject *module;
713 PyObject *result = NULL;
714 ret = _PyObject_LookupAttrId(x, &PyId___module__, &module);
715 if (module != NULL && module != Py_None) {
716 PyObject *builtinsname = _PyUnicode_FromId(&PyId_builtins);
717 if (builtinsname == NULL) {
718 goto done;
719 }
720 ret = PyObject_RichCompareBool(module, builtinsname, Py_NE);
721 if (ret < 0) {
722 // error
723 goto done;
724 }
725 if (ret > 0) {
726 result = PyUnicode_FromFormat("%S.%S()", module, qualname);
727 goto done;
728 }
729 }
730 else if (ret < 0) {
731 goto done;
732 }
733 result = PyUnicode_FromFormat("%S()", qualname);
734done:
735 Py_DECREF(qualname);
736 Py_XDECREF(module);
737 return result;
738}
739
Mark Dickinsonc008a172009-02-01 13:59:22 +0000740/* For Python 3.0.1 and later, the old three-way comparison has been
741 completely removed in favour of rich comparisons. PyObject_Compare() and
742 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200743 The old tp_compare slot has been renamed to tp_as_async, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000744 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000745
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000746 See (*) below for practical amendments.
747
Mark Dickinsonc008a172009-02-01 13:59:22 +0000748 tp_richcompare gets called with a first argument of the appropriate type
749 and a second object of an arbitrary type. We never do any kind of
750 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000751
Mark Dickinsonc008a172009-02-01 13:59:22 +0000752 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000753
754 NULL if an exception occurred
755 NotImplemented if the requested comparison is not implemented
756 any other false value if the requested comparison is false
757 any other true value if the requested comparison is true
758
759 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
760 NotImplemented.
761
762 (*) Practical amendments:
763
764 - If rich comparison returns NotImplemented, == and != are decided by
765 comparing the object pointer (i.e. falling back to the base object
766 implementation).
767
Guido van Rossuma4073002002-05-31 20:03:54 +0000768*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000769
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000770/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000771int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000772
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200773static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000774
775/* Perform a rich comparison, raising TypeError when the requested comparison
776 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000777static PyObject *
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100778do_richcompare(PyThreadState *tstate, PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 richcmpfunc f;
781 PyObject *res;
782 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (v->ob_type != w->ob_type &&
785 PyType_IsSubtype(w->ob_type, v->ob_type) &&
786 (f = w->ob_type->tp_richcompare) != NULL) {
787 checked_reverse_op = 1;
788 res = (*f)(w, v, _Py_SwappedOp[op]);
789 if (res != Py_NotImplemented)
790 return res;
791 Py_DECREF(res);
792 }
793 if ((f = v->ob_type->tp_richcompare) != NULL) {
794 res = (*f)(v, w, op);
795 if (res != Py_NotImplemented)
796 return res;
797 Py_DECREF(res);
798 }
799 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
800 res = (*f)(w, v, _Py_SwappedOp[op]);
801 if (res != Py_NotImplemented)
802 return res;
803 Py_DECREF(res);
804 }
805 /* If neither object implements it, provide a sensible default
806 for == and !=, but raise an exception for ordering. */
807 switch (op) {
808 case Py_EQ:
809 res = (v == w) ? Py_True : Py_False;
810 break;
811 case Py_NE:
812 res = (v != w) ? Py_True : Py_False;
813 break;
814 default:
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100815 _PyErr_Format(tstate, PyExc_TypeError,
816 "'%s' not supported between instances of '%.100s' and '%.100s'",
817 opstrings[op],
818 v->ob_type->tp_name,
819 w->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return NULL;
821 }
822 Py_INCREF(res);
823 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000824}
825
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000826/* Perform a rich comparison with object result. This wraps do_richcompare()
827 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000828
Guido van Rossume797ec12001-01-17 15:24:28 +0000829PyObject *
830PyObject_RichCompare(PyObject *v, PyObject *w, int op)
831{
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100832 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossume797ec12001-01-17 15:24:28 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 assert(Py_LT <= op && op <= Py_GE);
835 if (v == NULL || w == NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100836 if (!_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 PyErr_BadInternalCall();
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100838 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return NULL;
840 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100841 if (_Py_EnterRecursiveCall(tstate, " in comparison")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100843 }
844 PyObject *res = do_richcompare(tstate, v, w, op);
845 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000847}
848
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000849/* Perform a rich comparison with integer result. This wraps
850 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000851int
852PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 PyObject *res;
855 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 /* Quick result when objects are the same.
858 Guarantees that identity implies equality. */
859 if (v == w) {
860 if (op == Py_EQ)
861 return 1;
862 else if (op == Py_NE)
863 return 0;
864 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 res = PyObject_RichCompare(v, w, op);
867 if (res == NULL)
868 return -1;
869 if (PyBool_Check(res))
870 ok = (res == Py_True);
871 else
872 ok = PyObject_IsTrue(res);
873 Py_DECREF(res);
874 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000875}
Fred Drake13634cf2000-06-29 19:17:04 +0000876
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100877Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000878PyObject_HashNotImplemented(PyObject *v)
879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
881 Py_TYPE(v)->tp_name);
882 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000883}
Fred Drake13634cf2000-06-29 19:17:04 +0000884
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000885Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000886PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 PyTypeObject *tp = Py_TYPE(v);
889 if (tp->tp_hash != NULL)
890 return (*tp->tp_hash)(v);
891 /* To keep to the general practice that inheriting
892 * solely from object in C code should work without
893 * an explicit call to PyType_Ready, we implicitly call
894 * PyType_Ready here and then check the tp_hash slot again
895 */
896 if (tp->tp_dict == NULL) {
897 if (PyType_Ready(tp) < 0)
898 return -1;
899 if (tp->tp_hash != NULL)
900 return (*tp->tp_hash)(v);
901 }
902 /* Otherwise, the object can't be hashed */
903 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000904}
905
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000906PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000907PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 if (Py_TYPE(v)->tp_getattr != NULL)
912 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900913 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (w == NULL)
915 return NULL;
916 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100917 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000919}
920
921int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000922PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 PyObject *res = PyObject_GetAttrString(v, name);
925 if (res != NULL) {
926 Py_DECREF(res);
927 return 1;
928 }
929 PyErr_Clear();
930 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000931}
932
933int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000934PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyObject *s;
937 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (Py_TYPE(v)->tp_setattr != NULL)
940 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
941 s = PyUnicode_InternFromString(name);
942 if (s == NULL)
943 return -1;
944 res = PyObject_SetAttr(v, s, w);
945 Py_XDECREF(s);
946 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000947}
948
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500949int
950_PyObject_IsAbstract(PyObject *obj)
951{
952 int res;
953 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500954
955 if (obj == NULL)
956 return 0;
957
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200958 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
959 if (res > 0) {
960 res = PyObject_IsTrue(isabstract);
961 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500962 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500963 return res;
964}
965
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000966PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200967_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
968{
969 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100970 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200971 if (!oname)
972 return NULL;
973 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200974 return result;
975}
976
977int
978_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
979{
980 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100981 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200982 if (!oname)
983 return -1;
984 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200985 return result;
986}
987
988int
989_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
990{
991 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100992 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200993 if (!oname)
994 return -1;
995 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200996 return result;
997}
998
999PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001000PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (!PyUnicode_Check(name)) {
1005 PyErr_Format(PyExc_TypeError,
1006 "attribute name must be string, not '%.200s'",
1007 name->ob_type->tp_name);
1008 return NULL;
1009 }
1010 if (tp->tp_getattro != NULL)
1011 return (*tp->tp_getattro)(v, name);
1012 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001013 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (name_str == NULL)
1015 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001016 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 }
1018 PyErr_Format(PyExc_AttributeError,
1019 "'%.50s' object has no attribute '%U'",
1020 tp->tp_name, name);
1021 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001022}
1023
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001024int
1025_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +09001026{
1027 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +09001028
1029 if (!PyUnicode_Check(name)) {
1030 PyErr_Format(PyExc_TypeError,
1031 "attribute name must be string, not '%.200s'",
1032 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001033 *result = NULL;
1034 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +09001035 }
1036
1037 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001038 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
1039 if (*result != NULL) {
1040 return 1;
1041 }
1042 if (PyErr_Occurred()) {
1043 return -1;
1044 }
1045 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +09001046 }
1047 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001048 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +09001049 }
1050 else if (tp->tp_getattr != NULL) {
1051 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001052 if (name_str == NULL) {
1053 *result = NULL;
1054 return -1;
1055 }
1056 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +09001057 }
INADA Naokie76daeb2018-01-26 16:22:51 +09001058 else {
1059 *result = NULL;
1060 return 0;
1061 }
1062
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001063 if (*result != NULL) {
1064 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +09001065 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001066 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1067 return -1;
1068 }
1069 PyErr_Clear();
1070 return 0;
1071}
1072
1073int
1074_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
1075{
1076 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
1077 if (!oname) {
1078 *result = NULL;
1079 return -1;
1080 }
1081 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +09001082}
1083
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001084int
Fred Drake100814d2000-07-09 15:48:49 +00001085PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001086{
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001087 PyObject *res;
1088 if (_PyObject_LookupAttr(v, name, &res) < 0) {
1089 PyErr_Clear();
1090 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001092 if (res == NULL) {
1093 return 0;
1094 }
1095 Py_DECREF(res);
1096 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001097}
1098
1099int
Fred Drake100814d2000-07-09 15:48:49 +00001100PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyTypeObject *tp = Py_TYPE(v);
1103 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (!PyUnicode_Check(name)) {
1106 PyErr_Format(PyExc_TypeError,
1107 "attribute name must be string, not '%.200s'",
1108 name->ob_type->tp_name);
1109 return -1;
1110 }
1111 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyUnicode_InternInPlace(&name);
1114 if (tp->tp_setattro != NULL) {
1115 err = (*tp->tp_setattro)(v, name, value);
1116 Py_DECREF(name);
1117 return err;
1118 }
1119 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001120 const char *name_str = PyUnicode_AsUTF8(name);
Zackery Spytze0dcb852019-04-28 06:58:52 -06001121 if (name_str == NULL) {
1122 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 return -1;
Zackery Spytze0dcb852019-04-28 06:58:52 -06001124 }
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001125 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 Py_DECREF(name);
1127 return err;
1128 }
1129 Py_DECREF(name);
Victor Stinner24702042018-10-26 17:16:37 +02001130 _PyObject_ASSERT(name, name->ob_refcnt >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1132 PyErr_Format(PyExc_TypeError,
1133 "'%.100s' object has no attributes "
1134 "(%s .%U)",
1135 tp->tp_name,
1136 value==NULL ? "del" : "assign to",
1137 name);
1138 else
1139 PyErr_Format(PyExc_TypeError,
1140 "'%.100s' object has only read-only attributes "
1141 "(%s .%U)",
1142 tp->tp_name,
1143 value==NULL ? "del" : "assign to",
1144 name);
1145 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001146}
1147
1148/* Helper to get a pointer to an object's __dict__ slot, if any */
1149
1150PyObject **
1151_PyObject_GetDictPtr(PyObject *obj)
1152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 Py_ssize_t dictoffset;
1154 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 dictoffset = tp->tp_dictoffset;
1157 if (dictoffset == 0)
1158 return NULL;
1159 if (dictoffset < 0) {
1160 Py_ssize_t tsize;
1161 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 tsize = ((PyVarObject *)obj)->ob_size;
1164 if (tsize < 0)
1165 tsize = -tsize;
1166 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001169 _PyObject_ASSERT(obj, dictoffset > 0);
1170 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 }
1172 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001173}
1174
Tim Peters6d6c1a32001-08-02 04:15:00 +00001175PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001176PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 Py_INCREF(obj);
1179 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001180}
1181
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001182/* Helper used when the __next__ method is removed from a type:
1183 tp_iternext is never NULL and can be safely called without checking
1184 on every iteration.
1185 */
1186
1187PyObject *
1188_PyObject_NextNotImplemented(PyObject *self)
1189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 PyErr_Format(PyExc_TypeError,
1191 "'%.200s' object is not iterable",
1192 Py_TYPE(self)->tp_name);
1193 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001194}
1195
Yury Selivanovf2392132016-12-13 19:03:51 -05001196
1197/* Specialized version of _PyObject_GenericGetAttrWithDict
1198 specifically for the LOAD_METHOD opcode.
1199
1200 Return 1 if a method is found, 0 if it's a regular attribute
1201 from __dict__ or something returned by using a descriptor
1202 protocol.
1203
1204 `method` will point to the resolved attribute or NULL. In the
1205 latter case, an error will be set.
1206*/
1207int
1208_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1209{
1210 PyTypeObject *tp = Py_TYPE(obj);
1211 PyObject *descr;
1212 descrgetfunc f = NULL;
1213 PyObject **dictptr, *dict;
1214 PyObject *attr;
1215 int meth_found = 0;
1216
1217 assert(*method == NULL);
1218
1219 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1220 || !PyUnicode_Check(name)) {
1221 *method = PyObject_GetAttr(obj, name);
1222 return 0;
1223 }
1224
1225 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1226 return 0;
1227
1228 descr = _PyType_Lookup(tp, name);
1229 if (descr != NULL) {
1230 Py_INCREF(descr);
Jeroen Demeyereb65e242019-05-28 14:42:53 +02001231 if (PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001232 meth_found = 1;
1233 } else {
1234 f = descr->ob_type->tp_descr_get;
1235 if (f != NULL && PyDescr_IsData(descr)) {
1236 *method = f(descr, obj, (PyObject *)obj->ob_type);
1237 Py_DECREF(descr);
1238 return 0;
1239 }
1240 }
1241 }
1242
1243 dictptr = _PyObject_GetDictPtr(obj);
1244 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1245 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001246 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001247 if (attr != NULL) {
1248 Py_INCREF(attr);
1249 *method = attr;
1250 Py_DECREF(dict);
1251 Py_XDECREF(descr);
1252 return 0;
1253 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001254 else {
1255 Py_DECREF(dict);
1256 if (PyErr_Occurred()) {
1257 Py_XDECREF(descr);
1258 return 0;
1259 }
1260 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001261 }
1262
1263 if (meth_found) {
1264 *method = descr;
1265 return 1;
1266 }
1267
1268 if (f != NULL) {
1269 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1270 Py_DECREF(descr);
1271 return 0;
1272 }
1273
1274 if (descr != NULL) {
1275 *method = descr;
1276 return 0;
1277 }
1278
1279 PyErr_Format(PyExc_AttributeError,
1280 "'%.50s' object has no attribute '%U'",
1281 tp->tp_name, name);
1282 return 0;
1283}
1284
1285/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001286
Raymond Hettinger01538262003-03-17 08:24:35 +00001287PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001288_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1289 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001290{
Yury Selivanovf2392132016-12-13 19:03:51 -05001291 /* Make sure the logic of _PyObject_GetMethod is in sync with
1292 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001293
1294 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001295 */
1296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 PyTypeObject *tp = Py_TYPE(obj);
1298 PyObject *descr = NULL;
1299 PyObject *res = NULL;
1300 descrgetfunc f;
1301 Py_ssize_t dictoffset;
1302 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 if (!PyUnicode_Check(name)){
1305 PyErr_Format(PyExc_TypeError,
1306 "attribute name must be string, not '%.200s'",
1307 name->ob_type->tp_name);
1308 return NULL;
1309 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001310 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (tp->tp_dict == NULL) {
1313 if (PyType_Ready(tp) < 0)
1314 goto done;
1315 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 f = NULL;
1320 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001321 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 f = descr->ob_type->tp_descr_get;
1323 if (f != NULL && PyDescr_IsData(descr)) {
1324 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001325 if (res == NULL && suppress &&
1326 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1327 PyErr_Clear();
1328 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 goto done;
1330 }
1331 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001333 if (dict == NULL) {
1334 /* Inline _PyObject_GetDictPtr */
1335 dictoffset = tp->tp_dictoffset;
1336 if (dictoffset != 0) {
1337 if (dictoffset < 0) {
1338 Py_ssize_t tsize;
1339 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001340
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001341 tsize = ((PyVarObject *)obj)->ob_size;
1342 if (tsize < 0)
1343 tsize = -tsize;
1344 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001345 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001346
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001347 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001348 _PyObject_ASSERT(obj, dictoffset > 0);
1349 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001351 dictptr = (PyObject **) ((char *)obj + dictoffset);
1352 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 }
1354 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001355 if (dict != NULL) {
1356 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001357 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001358 if (res != NULL) {
1359 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001360 Py_DECREF(dict);
1361 goto done;
1362 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001363 else {
1364 Py_DECREF(dict);
1365 if (PyErr_Occurred()) {
1366 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1367 PyErr_Clear();
1368 }
1369 else {
1370 goto done;
1371 }
1372 }
1373 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001374 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (f != NULL) {
1377 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001378 if (res == NULL && suppress &&
1379 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1380 PyErr_Clear();
1381 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 goto done;
1383 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (descr != NULL) {
1386 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001387 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 goto done;
1389 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001390
INADA Naoki378edee2018-01-16 20:52:41 +09001391 if (!suppress) {
1392 PyErr_Format(PyExc_AttributeError,
1393 "'%.50s' object has no attribute '%U'",
1394 tp->tp_name, name);
1395 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001396 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001397 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 Py_DECREF(name);
1399 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001400}
1401
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001402PyObject *
1403PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1404{
INADA Naoki378edee2018-01-16 20:52:41 +09001405 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001406}
1407
Tim Peters6d6c1a32001-08-02 04:15:00 +00001408int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001409_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1410 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyTypeObject *tp = Py_TYPE(obj);
1413 PyObject *descr;
1414 descrsetfunc f;
1415 PyObject **dictptr;
1416 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!PyUnicode_Check(name)){
1419 PyErr_Format(PyExc_TypeError,
1420 "attribute name must be string, not '%.200s'",
1421 name->ob_type->tp_name);
1422 return -1;
1423 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001424
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001425 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1426 return -1;
1427
1428 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001433 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001435 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 res = f(descr, obj, value);
1437 goto done;
1438 }
1439 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001440
Steve Dowerb82e17e2019-05-23 08:45:22 -07001441 /* XXX [Steve Dower] These are really noisy - worth it? */
1442 /*if (PyType_Check(obj) || PyModule_Check(obj)) {
1443 if (value && PySys_Audit("object.__setattr__", "OOO", obj, name, value) < 0)
1444 return -1;
1445 if (!value && PySys_Audit("object.__delattr__", "OO", obj, name) < 0)
1446 return -1;
1447 }*/
1448
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001449 if (dict == NULL) {
1450 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001451 if (dictptr == NULL) {
1452 if (descr == NULL) {
1453 PyErr_Format(PyExc_AttributeError,
1454 "'%.100s' object has no attribute '%U'",
1455 tp->tp_name, name);
1456 }
1457 else {
1458 PyErr_Format(PyExc_AttributeError,
1459 "'%.50s' object attribute '%U' is read-only",
1460 tp->tp_name, name);
1461 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001462 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001464 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001465 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001466 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001467 Py_INCREF(dict);
1468 if (value == NULL)
1469 res = PyDict_DelItem(dict, name);
1470 else
1471 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001472 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001474 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1475 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001477 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001478 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 Py_DECREF(name);
1480 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001481}
1482
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001483int
1484PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1485{
1486 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1487}
1488
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001489int
1490PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1491{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001492 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001493 if (dictptr == NULL) {
1494 PyErr_SetString(PyExc_AttributeError,
1495 "This object has no __dict__");
1496 return -1;
1497 }
1498 if (value == NULL) {
1499 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1500 return -1;
1501 }
1502 if (!PyDict_Check(value)) {
1503 PyErr_Format(PyExc_TypeError,
1504 "__dict__ must be set to a dictionary, "
1505 "not a '%.200s'", Py_TYPE(value)->tp_name);
1506 return -1;
1507 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001508 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001509 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001510 return 0;
1511}
1512
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001513
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001514/* Test a value used as condition, e.g., in a for or if statement.
1515 Return -1 if an error occurred */
1516
1517int
Fred Drake100814d2000-07-09 15:48:49 +00001518PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 Py_ssize_t res;
1521 if (v == Py_True)
1522 return 1;
1523 if (v == Py_False)
1524 return 0;
1525 if (v == Py_None)
1526 return 0;
1527 else if (v->ob_type->tp_as_number != NULL &&
1528 v->ob_type->tp_as_number->nb_bool != NULL)
1529 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1530 else if (v->ob_type->tp_as_mapping != NULL &&
1531 v->ob_type->tp_as_mapping->mp_length != NULL)
1532 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1533 else if (v->ob_type->tp_as_sequence != NULL &&
1534 v->ob_type->tp_as_sequence->sq_length != NULL)
1535 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1536 else
1537 return 1;
1538 /* if it is negative, it should be either -1 or -2 */
1539 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001540}
1541
Tim Peters803526b2002-07-07 05:13:56 +00001542/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001543 Return -1 if an error occurred */
1544
1545int
Fred Drake100814d2000-07-09 15:48:49 +00001546PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 int res;
1549 res = PyObject_IsTrue(v);
1550 if (res < 0)
1551 return res;
1552 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001553}
1554
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001555/* Test whether an object can be called */
1556
1557int
Fred Drake100814d2000-07-09 15:48:49 +00001558PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (x == NULL)
1561 return 0;
1562 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001563}
1564
Tim Peters7eea37e2001-09-04 22:08:56 +00001565
Georg Brandle32b4222007-03-10 22:13:27 +00001566/* Helper for PyObject_Dir without arguments: returns the local scope. */
1567static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001568_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001571 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001572
Victor Stinner41bb43a2013-10-29 01:19:37 +01001573 locals = PyEval_GetLocals();
1574 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 names = PyMapping_Keys(locals);
1578 if (!names)
1579 return NULL;
1580 if (!PyList_Check(names)) {
1581 PyErr_Format(PyExc_TypeError,
1582 "dir(): expected keys() of locals to be a list, "
1583 "not '%.200s'", Py_TYPE(names)->tp_name);
1584 Py_DECREF(names);
1585 return NULL;
1586 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001587 if (PyList_Sort(names)) {
1588 Py_DECREF(names);
1589 return NULL;
1590 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 /* the locals don't need to be DECREF'd */
1592 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001593}
1594
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001595/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001596static PyObject *
1597_dir_object(PyObject *obj)
1598{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001599 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001600 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001601
Victor Stinner24702042018-10-26 17:16:37 +02001602 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001604 if (!PyErr_Occurred())
1605 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1606 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001608 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001609 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001610 Py_DECREF(dirfunc);
1611 if (result == NULL)
1612 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001613 /* return sorted(result) */
1614 sorted = PySequence_List(result);
1615 Py_DECREF(result);
1616 if (sorted == NULL)
1617 return NULL;
1618 if (PyList_Sort(sorted)) {
1619 Py_DECREF(sorted);
1620 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001622 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001623}
1624
1625/* Implementation of dir() -- if obj is NULL, returns the names in the current
1626 (local) scope. Otherwise, performs introspection of the object: returns a
1627 sorted list of attribute names (supposedly) accessible from the object
1628*/
1629PyObject *
1630PyObject_Dir(PyObject *obj)
1631{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001632 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001633}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001634
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001635/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001636None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001637There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001638so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001639*/
1640
Guido van Rossum0c182a11992-03-27 17:26:13 +00001641/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001642static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001643none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001646}
1647
Barry Warsaw9bf16442001-01-23 16:24:35 +00001648/* ARGUSED */
Victor Stinner2a4903f2020-01-30 13:09:11 +01001649static void _Py_NO_RETURN
Tim Peters803526b2002-07-07 05:13:56 +00001650none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* This should never get called, but we also don't want to SEGV if
1653 * we accidentally decref None out of existence.
1654 */
1655 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001656}
1657
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001658static PyObject *
1659none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1660{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001661 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001662 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1663 return NULL;
1664 }
1665 Py_RETURN_NONE;
1666}
1667
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001668static int
1669none_bool(PyObject *v)
1670{
1671 return 0;
1672}
1673
1674static PyNumberMethods none_as_number = {
1675 0, /* nb_add */
1676 0, /* nb_subtract */
1677 0, /* nb_multiply */
1678 0, /* nb_remainder */
1679 0, /* nb_divmod */
1680 0, /* nb_power */
1681 0, /* nb_negative */
1682 0, /* nb_positive */
1683 0, /* nb_absolute */
1684 (inquiry)none_bool, /* nb_bool */
1685 0, /* nb_invert */
1686 0, /* nb_lshift */
1687 0, /* nb_rshift */
1688 0, /* nb_and */
1689 0, /* nb_xor */
1690 0, /* nb_or */
1691 0, /* nb_int */
1692 0, /* nb_reserved */
1693 0, /* nb_float */
1694 0, /* nb_inplace_add */
1695 0, /* nb_inplace_subtract */
1696 0, /* nb_inplace_multiply */
1697 0, /* nb_inplace_remainder */
1698 0, /* nb_inplace_power */
1699 0, /* nb_inplace_lshift */
1700 0, /* nb_inplace_rshift */
1701 0, /* nb_inplace_and */
1702 0, /* nb_inplace_xor */
1703 0, /* nb_inplace_or */
1704 0, /* nb_floor_divide */
1705 0, /* nb_true_divide */
1706 0, /* nb_inplace_floor_divide */
1707 0, /* nb_inplace_true_divide */
1708 0, /* nb_index */
1709};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001710
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001711PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1713 "NoneType",
1714 0,
1715 0,
1716 none_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001717 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 0, /*tp_getattr*/
1719 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001720 0, /*tp_as_async*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001722 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 0, /*tp_as_sequence*/
1724 0, /*tp_as_mapping*/
1725 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001726 0, /*tp_call */
1727 0, /*tp_str */
1728 0, /*tp_getattro */
1729 0, /*tp_setattro */
1730 0, /*tp_as_buffer */
1731 Py_TPFLAGS_DEFAULT, /*tp_flags */
1732 0, /*tp_doc */
1733 0, /*tp_traverse */
1734 0, /*tp_clear */
1735 0, /*tp_richcompare */
1736 0, /*tp_weaklistoffset */
1737 0, /*tp_iter */
1738 0, /*tp_iternext */
1739 0, /*tp_methods */
1740 0, /*tp_members */
1741 0, /*tp_getset */
1742 0, /*tp_base */
1743 0, /*tp_dict */
1744 0, /*tp_descr_get */
1745 0, /*tp_descr_set */
1746 0, /*tp_dictoffset */
1747 0, /*tp_init */
1748 0, /*tp_alloc */
1749 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750};
1751
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001752PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001753 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001754 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001755};
1756
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001757/* NotImplemented is an object that can be used to signal that an
1758 operation is not implemented for the given type combination. */
1759
1760static PyObject *
1761NotImplemented_repr(PyObject *op)
1762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001764}
1765
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001766static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301767NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001768{
1769 return PyUnicode_FromString("NotImplemented");
1770}
1771
1772static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301773 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001774 {NULL, NULL}
1775};
1776
1777static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001778notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1779{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001780 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001781 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1782 return NULL;
1783 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001784 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001785}
1786
Victor Stinner2a4903f2020-01-30 13:09:11 +01001787static void _Py_NO_RETURN
Armin Ronacher226b1db2012-10-06 14:28:58 +02001788notimplemented_dealloc(PyObject* ignore)
1789{
1790 /* This should never get called, but we also don't want to SEGV if
1791 * we accidentally decref NotImplemented out of existence.
1792 */
1793 Py_FatalError("deallocating NotImplemented");
1794}
1795
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001796PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1798 "NotImplementedType",
1799 0,
1800 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001801 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001802 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 0, /*tp_getattr*/
1804 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001805 0, /*tp_as_async*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 NotImplemented_repr, /*tp_repr*/
1807 0, /*tp_as_number*/
1808 0, /*tp_as_sequence*/
1809 0, /*tp_as_mapping*/
1810 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001811 0, /*tp_call */
1812 0, /*tp_str */
1813 0, /*tp_getattro */
1814 0, /*tp_setattro */
1815 0, /*tp_as_buffer */
1816 Py_TPFLAGS_DEFAULT, /*tp_flags */
1817 0, /*tp_doc */
1818 0, /*tp_traverse */
1819 0, /*tp_clear */
1820 0, /*tp_richcompare */
1821 0, /*tp_weaklistoffset */
1822 0, /*tp_iter */
1823 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001824 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001825 0, /*tp_members */
1826 0, /*tp_getset */
1827 0, /*tp_base */
1828 0, /*tp_dict */
1829 0, /*tp_descr_get */
1830 0, /*tp_descr_set */
1831 0, /*tp_dictoffset */
1832 0, /*tp_init */
1833 0, /*tp_alloc */
1834 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001835};
1836
1837PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001839 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001840};
1841
Victor Stinner331a6a52019-05-27 16:39:22 +02001842PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01001843_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001844{
Victor Stinner7a1f6c22020-01-30 09:02:14 +01001845 PyStatus status = _PyTypes_InitSlotDefs();
1846 if (_PyStatus_EXCEPTION(status)) {
1847 return status;
1848 }
1849
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001850#define INIT_TYPE(TYPE, NAME) \
1851 do { \
1852 if (PyType_Ready(TYPE) < 0) { \
Victor Stinner331a6a52019-05-27 16:39:22 +02001853 return _PyStatus_ERR("Can't initialize " NAME " type"); \
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001854 } \
1855 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001856
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001857 INIT_TYPE(&PyBaseObject_Type, "object");
1858 INIT_TYPE(&PyType_Type, "type");
1859 INIT_TYPE(&_PyWeakref_RefType, "weakref");
1860 INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
1861 INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
1862 INIT_TYPE(&PyLong_Type, "int");
1863 INIT_TYPE(&PyBool_Type, "bool");
1864 INIT_TYPE(&PyByteArray_Type, "bytearray");
1865 INIT_TYPE(&PyBytes_Type, "str");
1866 INIT_TYPE(&PyList_Type, "list");
1867 INIT_TYPE(&_PyNone_Type, "None");
1868 INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
1869 INIT_TYPE(&PyTraceBack_Type, "traceback");
1870 INIT_TYPE(&PySuper_Type, "super");
1871 INIT_TYPE(&PyRange_Type, "range");
1872 INIT_TYPE(&PyDict_Type, "dict");
1873 INIT_TYPE(&PyDictKeys_Type, "dict keys");
1874 INIT_TYPE(&PyDictValues_Type, "dict values");
1875 INIT_TYPE(&PyDictItems_Type, "dict items");
1876 INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
1877 INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
1878 INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
1879 INIT_TYPE(&PyODict_Type, "OrderedDict");
1880 INIT_TYPE(&PyODictKeys_Type, "odict_keys");
1881 INIT_TYPE(&PyODictItems_Type, "odict_items");
1882 INIT_TYPE(&PyODictValues_Type, "odict_values");
1883 INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
1884 INIT_TYPE(&PySet_Type, "set");
1885 INIT_TYPE(&PyUnicode_Type, "str");
1886 INIT_TYPE(&PySlice_Type, "slice");
1887 INIT_TYPE(&PyStaticMethod_Type, "static method");
1888 INIT_TYPE(&PyComplex_Type, "complex");
1889 INIT_TYPE(&PyFloat_Type, "float");
1890 INIT_TYPE(&PyFrozenSet_Type, "frozenset");
1891 INIT_TYPE(&PyProperty_Type, "property");
1892 INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
1893 INIT_TYPE(&PyMemoryView_Type, "memoryview");
1894 INIT_TYPE(&PyTuple_Type, "tuple");
1895 INIT_TYPE(&PyEnum_Type, "enumerate");
1896 INIT_TYPE(&PyReversed_Type, "reversed");
1897 INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
1898 INIT_TYPE(&PyCode_Type, "code");
1899 INIT_TYPE(&PyFrame_Type, "frame");
1900 INIT_TYPE(&PyCFunction_Type, "builtin function");
1901 INIT_TYPE(&PyMethod_Type, "method");
1902 INIT_TYPE(&PyFunction_Type, "function");
1903 INIT_TYPE(&PyDictProxy_Type, "dict proxy");
1904 INIT_TYPE(&PyGen_Type, "generator");
1905 INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
1906 INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
1907 INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
1908 INIT_TYPE(&PyEllipsis_Type, "ellipsis");
1909 INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
1910 INIT_TYPE(&_PyNamespace_Type, "namespace");
1911 INIT_TYPE(&PyCapsule_Type, "capsule");
1912 INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
1913 INIT_TYPE(&PyCell_Type, "cell");
1914 INIT_TYPE(&PyInstanceMethod_Type, "instance method");
1915 INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
1916 INIT_TYPE(&PyMethodDescr_Type, "method descr");
1917 INIT_TYPE(&PyCallIter_Type, "call iter");
1918 INIT_TYPE(&PySeqIter_Type, "sequence iterator");
Antoine Pitrou91f43802019-05-26 17:10:09 +02001919 INIT_TYPE(&PyPickleBuffer_Type, "pickle.PickleBuffer");
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001920 INIT_TYPE(&PyCoro_Type, "coroutine");
1921 INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
Eric Snowc11183c2019-03-15 16:35:46 -06001922 INIT_TYPE(&_PyInterpreterID_Type, "interpreter ID");
Victor Stinner331a6a52019-05-27 16:39:22 +02001923 return _PyStatus_OK();
Guido van Rossumba21a492001-08-16 08:17:26 +00001924
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001925#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001926}
1927
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001928
Guido van Rossum84a90321996-05-22 16:34:47 +00001929#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001930
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001931void
Fred Drake100814d2000-07-09 15:48:49 +00001932_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001933{
Victor Stinner9e00e802018-10-25 13:31:16 +02001934 if (_Py_tracemalloc_config.tracing) {
1935 _PyTraceMalloc_NewReference(op);
1936 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 _Py_INC_REFTOTAL;
1938 op->ob_refcnt = 1;
1939 _Py_AddToAllObjects(op, 1);
1940 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001941}
1942
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001943void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001944_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001945{
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001946 if (op->ob_refcnt < 0) {
1947 _PyObject_ASSERT_FAILED_MSG(op, "negative refcnt");
1948 }
1949
1950 if (op == &refchain ||
1951 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
1952 {
1953 _PyObject_ASSERT_FAILED_MSG(op, "invalid object chain");
1954 }
1955
Guido van Rossumbffd6832000-01-20 22:32:56 +00001956#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001957 PyObject *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001959 if (p == op) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 break;
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001961 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 }
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001963 if (p == &refchain) {
1964 /* Not found */
1965 _PyObject_ASSERT_FAILED_MSG(op,
1966 "object not found in the objects list");
1967 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001968#endif
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 op->_ob_next->_ob_prev = op->_ob_prev;
1971 op->_ob_prev->_ob_next = op->_ob_next;
1972 op->_ob_next = op->_ob_prev = NULL;
1973 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001974}
1975
Tim Peters269b2a62003-04-17 19:52:29 +00001976/* Print all live objects. Because PyObject_Print is called, the
1977 * interpreter must be in a healthy state.
1978 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001979void
Fred Drake100814d2000-07-09 15:48:49 +00001980_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 PyObject *op;
1983 fprintf(fp, "Remaining objects:\n");
1984 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001985 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", (void *)op, op->ob_refcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (PyObject_Print(op, fp, 0) != 0)
1987 PyErr_Clear();
1988 putc('\n', fp);
1989 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001990}
1991
Tim Peters269b2a62003-04-17 19:52:29 +00001992/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1993 * doesn't make any calls to the Python C API, so is always safe to call.
1994 */
1995void
1996_Py_PrintReferenceAddresses(FILE *fp)
1997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 PyObject *op;
1999 fprintf(fp, "Remaining object addresses:\n");
2000 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002001 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", (void *)op,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00002003}
2004
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002005PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002006_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 int i, n;
2009 PyObject *t = NULL;
2010 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2013 return NULL;
2014 op = refchain._ob_next;
2015 res = PyList_New(0);
2016 if (res == NULL)
2017 return NULL;
2018 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2019 while (op == self || op == args || op == res || op == t ||
2020 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2021 op = op->_ob_next;
2022 if (op == &refchain)
2023 return res;
2024 }
2025 if (PyList_Append(res, op) < 0) {
2026 Py_DECREF(res);
2027 return NULL;
2028 }
2029 op = op->_ob_next;
2030 }
2031 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002032}
2033
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002034#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002035
Benjamin Petersonb173f782009-05-05 22:31:58 +00002036
Guido van Rossum84a90321996-05-22 16:34:47 +00002037/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002038Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002039
2040
David Malcolm49526f42012-06-22 14:55:41 -04002041void
2042_PyObject_DebugTypeStats(FILE *out)
2043{
David Malcolm49526f42012-06-22 14:55:41 -04002044 _PyDict_DebugMallocStats(out);
2045 _PyFloat_DebugMallocStats(out);
2046 _PyFrame_DebugMallocStats(out);
2047 _PyList_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04002048 _PyTuple_DebugMallocStats(out);
2049}
Guido van Rossumb18618d2000-05-03 23:44:39 +00002050
Guido van Rossum86610361998-04-10 22:32:46 +00002051/* These methods are used to control infinite recursion in repr, str, print,
2052 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00002053 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00002054 Py_ReprLeave() to avoid infinite recursion.
2055
2056 Py_ReprEnter() returns 0 the first time it is called for a particular
2057 object and 1 every time thereafter. It returns -1 if an exception
2058 occurred. Py_ReprLeave() has no return value.
2059
2060 See dictobject.c and listobject.c for examples of use.
2061*/
2062
Guido van Rossum86610361998-04-10 22:32:46 +00002063int
Fred Drake100814d2000-07-09 15:48:49 +00002064Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 PyObject *dict;
2067 PyObject *list;
2068 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02002071 /* Ignore a missing thread-state, so that this function can be called
2072 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (dict == NULL)
2074 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002075 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002077 if (PyErr_Occurred()) {
2078 return -1;
2079 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 list = PyList_New(0);
2081 if (list == NULL)
2082 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01002083 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 return -1;
2085 Py_DECREF(list);
2086 }
2087 i = PyList_GET_SIZE(list);
2088 while (--i >= 0) {
2089 if (PyList_GET_ITEM(list, i) == obj)
2090 return 1;
2091 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002092 if (PyList_Append(list, obj) < 0)
2093 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002095}
2096
2097void
Fred Drake100814d2000-07-09 15:48:49 +00002098Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 PyObject *dict;
2101 PyObject *list;
2102 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002103 PyObject *error_type, *error_value, *error_traceback;
2104
2105 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 dict = PyThreadState_GetDict();
2108 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002109 goto finally;
2110
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002111 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002113 goto finally;
2114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 i = PyList_GET_SIZE(list);
2116 /* Count backwards because we always expect obj to be list[-1] */
2117 while (--i >= 0) {
2118 if (PyList_GET_ITEM(list, i) == obj) {
2119 PyList_SetSlice(list, i, i + 1, NULL);
2120 break;
2121 }
2122 }
Victor Stinner1b634932013-07-16 22:24:44 +02002123
2124finally:
2125 /* ignore exceptions because there is no way to report them. */
2126 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002127}
Guido van Rossumd724b232000-03-13 16:01:29 +00002128
Tim Peters803526b2002-07-07 05:13:56 +00002129/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002130
Tim Peters803526b2002-07-07 05:13:56 +00002131/* Add op to the _PyTrash_delete_later list. Called when the current
2132 * call-stack depth gets large. op must be a currently untracked gc'ed
2133 * object, with refcount 0. Py_DECREF must already have been called on it.
2134 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002135void
Fred Drake100814d2000-07-09 15:48:49 +00002136_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002137{
Victor Stinner72474072019-11-20 12:25:50 +01002138 PyThreadState *tstate = _PyThreadState_GET();
2139 struct _gc_runtime_state *gcstate = &tstate->interp->gc;
2140
Victor Stinner24702042018-10-26 17:16:37 +02002141 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2142 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2143 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Victor Stinner72474072019-11-20 12:25:50 +01002144 _PyGCHead_SET_PREV(_Py_AS_GC(op), gcstate->trash_delete_later);
2145 gcstate->trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002146}
2147
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002148/* The equivalent API, using per-thread state recursion info */
2149void
2150_PyTrash_thread_deposit_object(PyObject *op)
2151{
Victor Stinner50b48572018-11-01 01:51:40 +01002152 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002153 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2154 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2155 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002156 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002157 tstate->trash_delete_later = op;
2158}
2159
Min ho Kimc4cacc82019-07-31 08:16:13 +10002160/* Deallocate all the objects in the _PyTrash_delete_later list. Called when
Tim Peters803526b2002-07-07 05:13:56 +00002161 * the call-stack unwinds again.
2162 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002163void
Fred Drake100814d2000-07-09 15:48:49 +00002164_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002165{
Victor Stinner72474072019-11-20 12:25:50 +01002166 PyThreadState *tstate = _PyThreadState_GET();
2167 struct _gc_runtime_state *gcstate = &tstate->interp->gc;
2168
2169 while (gcstate->trash_delete_later) {
2170 PyObject *op = gcstate->trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002172
Victor Stinner72474072019-11-20 12:25:50 +01002173 gcstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002174 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 /* Call the deallocator directly. This used to try to
2177 * fool Py_DECREF into calling it indirectly, but
2178 * Py_DECREF was already called on this object, and in
2179 * assorted non-release builds calling Py_DECREF again ends
2180 * up distorting allocation statistics.
2181 */
Victor Stinner24702042018-10-26 17:16:37 +02002182 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Victor Stinner72474072019-11-20 12:25:50 +01002183 ++gcstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 (*dealloc)(op);
Victor Stinner72474072019-11-20 12:25:50 +01002185 --gcstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002187}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002188
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002189/* The equivalent API, using per-thread state recursion info */
2190void
2191_PyTrash_thread_destroy_chain(void)
2192{
Victor Stinner50b48572018-11-01 01:51:40 +01002193 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002194 /* We need to increase trash_delete_nesting here, otherwise,
2195 _PyTrash_thread_destroy_chain will be called recursively
2196 and then possibly crash. An example that may crash without
2197 increase:
2198 N = 500000 # need to be large enough
2199 ob = object()
2200 tups = [(ob,) for i in range(N)]
2201 for i in range(49):
2202 tups = [(tup,) for tup in tups]
2203 del tups
2204 */
2205 assert(tstate->trash_delete_nesting == 0);
2206 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002207 while (tstate->trash_delete_later) {
2208 PyObject *op = tstate->trash_delete_later;
2209 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2210
2211 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002212 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002213
2214 /* Call the deallocator directly. This used to try to
2215 * fool Py_DECREF into calling it indirectly, but
2216 * Py_DECREF was already called on this object, and in
2217 * assorted non-release builds calling Py_DECREF again ends
2218 * up distorting allocation statistics.
2219 */
Victor Stinner24702042018-10-26 17:16:37 +02002220 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002221 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002222 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002223 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002224 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002225}
2226
Victor Stinner626bff82018-10-25 17:31:10 +02002227
Victor Stinner2a4903f2020-01-30 13:09:11 +01002228void _Py_NO_RETURN
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002229_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002230 const char *file, int line, const char *function)
2231{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002232 fprintf(stderr, "%s:%d: ", file, line);
2233 if (function) {
2234 fprintf(stderr, "%s: ", function);
2235 }
Victor Stinner626bff82018-10-25 17:31:10 +02002236 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002237
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002238 if (expr) {
2239 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002240 }
2241 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002242 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002243 }
2244 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002245
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002246 if (msg) {
2247 fprintf(stderr, ": %s", msg);
2248 }
2249 fprintf(stderr, "\n");
2250 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002251
Victor Stinner68762572019-10-07 18:42:01 +02002252 if (_PyObject_IsFreed(obj)) {
Victor Stinner626bff82018-10-25 17:31:10 +02002253 /* It seems like the object memory has been freed:
2254 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +02002255 fprintf(stderr, "<object at %p is freed>\n", obj);
Victor Stinner68762572019-10-07 18:42:01 +02002256 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002257 }
2258 else {
penguindustin96466302019-05-06 14:57:17 -04002259 /* Display the traceback where the object has been allocated.
Victor Stinner626bff82018-10-25 17:31:10 +02002260 Do it before dumping repr(obj), since repr() is more likely
2261 to crash than dumping the traceback. */
2262 void *ptr;
2263 PyTypeObject *type = Py_TYPE(obj);
2264 if (PyType_IS_GC(type)) {
2265 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2266 }
2267 else {
2268 ptr = (void *)obj;
2269 }
2270 _PyMem_DumpTraceback(fileno(stderr), ptr);
2271
2272 /* This might succeed or fail, but we're about to abort, so at least
2273 try to provide any extra info we can: */
2274 _PyObject_Dump(obj);
Victor Stinner77753492019-10-07 23:44:05 +02002275
2276 fprintf(stderr, "\n");
2277 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002278 }
Victor Stinner626bff82018-10-25 17:31:10 +02002279
2280 Py_FatalError("_PyObject_AssertFailed");
2281}
2282
Victor Stinner3c09dca2018-10-30 14:48:26 +01002283
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002284#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002285
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002286void
2287_Py_Dealloc(PyObject *op)
2288{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002289 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2290#ifdef Py_TRACE_REFS
2291 _Py_ForgetReference(op);
2292#else
2293 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002294#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002295 (*dealloc)(op);
2296}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002297
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002298#ifdef __cplusplus
2299}
2300#endif