blob: 604f5e0d488259c310a7c50c6d749a215d7cfa1d [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 Stinner871ff772019-05-17 23:54:00 +02005#include "pycore_coreconfig.h"
Victor Stinner0fc91ee2019-04-12 21:51:34 +02006#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pystate.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01008#include "pycore_context.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00009#include "frameobject.h"
Eric Snowc11183c2019-03-15 16:35:46 -060010#include "interpreteridobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012#ifdef __cplusplus
13extern "C" {
14#endif
15
Victor Stinner626bff82018-10-25 17:31:10 +020016/* Defined in tracemalloc.c */
17extern void _PyMem_DumpTraceback(int fd, const void *ptr);
18
Victor Stinnerbd303c12013-11-07 23:07:29 +010019_Py_IDENTIFIER(Py_Repr);
20_Py_IDENTIFIER(__bytes__);
21_Py_IDENTIFIER(__dir__);
22_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010023
Victor Stinner0fc91ee2019-04-12 21:51:34 +020024
25int
26_PyObject_CheckConsistency(PyObject *op, int check_content)
27{
28 _PyObject_ASSERT(op, op != NULL);
29 _PyObject_ASSERT(op, !_PyObject_IsFreed(op));
30 _PyObject_ASSERT(op, Py_REFCNT(op) >= 1);
31
32 PyTypeObject *type = op->ob_type;
33 _PyObject_ASSERT(op, type != NULL);
34 _PyType_CheckConsistency(type);
35
36 if (PyUnicode_Check(op)) {
37 _PyUnicode_CheckConsistency(op, check_content);
38 }
39 else if (PyDict_Check(op)) {
40 _PyDict_CheckConsistency(op, check_content);
41 }
42 return 1;
43}
44
45
Tim Peters34592512002-07-11 06:23:50 +000046#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000047Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048
49Py_ssize_t
50_Py_GetRefTotal(void)
51{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 PyObject *o;
53 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020054 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 if (o != NULL)
56 total -= o->ob_refcnt;
57 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058}
Nick Coghland6009512014-11-20 21:39:37 +100059
60void
61_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070062 fprintf(stderr,
63 "[%" PY_FORMAT_SIZE_T "d refs, "
64 "%" PY_FORMAT_SIZE_T "d blocks]\n",
65 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100066}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000067#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068
Guido van Rossum3f5da241990-12-20 15:06:42 +000069/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
70 These are used by the individual routines for object creation.
71 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072
Tim Peters78be7992003-03-23 02:51:01 +000073#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000074/* Head of circular doubly-linked list of all objects. These are linked
75 * together via the _ob_prev and _ob_next members of a PyObject, which
76 * exist only in a Py_TRACE_REFS build.
77 */
Tim Peters78be7992003-03-23 02:51:01 +000078static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000079
Tim Peters7571a0f2003-03-23 17:52:28 +000080/* Insert op at the front of the list of all objects. If force is true,
81 * op is added even if _ob_prev and _ob_next are non-NULL already. If
82 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
83 * force should be true if and only if op points to freshly allocated,
84 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000085 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000086 * Note that objects are normally added to the list via _Py_NewReference,
87 * which is called by PyObject_Init. Not all objects are initialized that
88 * way, though; exceptions include statically allocated type objects, and
89 * statically allocated singletons (like Py_True and Py_None).
90 */
Tim Peters36eb4df2003-03-23 03:33:13 +000091void
Tim Peters7571a0f2003-03-23 17:52:28 +000092_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000093{
Tim Peters7571a0f2003-03-23 17:52:28 +000094#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 if (!force) {
96 /* If it's initialized memory, op must be in or out of
97 * the list unambiguously.
98 */
Victor Stinner24702042018-10-26 17:16:37 +020099 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 }
Tim Peters78be7992003-03-23 02:51:01 +0000101#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 if (force || op->_ob_prev == NULL) {
103 op->_ob_next = refchain._ob_next;
104 op->_ob_prev = &refchain;
105 refchain._ob_next->_ob_prev = op;
106 refchain._ob_next = op;
107 }
Tim Peters7571a0f2003-03-23 17:52:28 +0000108}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +0000110
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000111#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000113/* All types are added to type_list, at least when
114 they get one object created. That makes them
115 immortal, which unfortunately contributes to
116 garbage itself. If unlist_types_without_objects
117 is set, they will be removed from the type_list
118 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +0000119static int unlist_types_without_objects;
Pablo Galindo49c75a82018-10-28 15:02:17 +0000120extern Py_ssize_t _Py_tuple_zero_allocs, _Py_fast_tuple_allocs;
121extern Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
122extern Py_ssize_t _Py_null_strings, _Py_one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000123void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000124_Py_dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000125{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200126 PyInterpreterState *interp = _PyInterpreterState_Get();
Eddie Elizondo745dc652018-02-21 20:55:18 -0800127 if (!interp->core_config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300128 return;
Victor Stinner25420fe2017-11-20 18:12:22 -0800129 }
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000130
Eddie Elizondo745dc652018-02-21 20:55:18 -0800131 PyTypeObject *tp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 for (tp = type_list; tp; tp = tp->tp_next)
133 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
134 "freed: %" PY_FORMAT_SIZE_T "d, "
135 "max in use: %" PY_FORMAT_SIZE_T "d\n",
136 tp->tp_name, tp->tp_allocs, tp->tp_frees,
137 tp->tp_maxalloc);
138 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
139 "empty: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000140 _Py_fast_tuple_allocs, _Py_tuple_zero_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
142 "neg: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000143 _Py_quick_int_allocs, _Py_quick_neg_int_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
145 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000146 _Py_null_strings, _Py_one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000147}
148
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000149PyObject *
Pablo Galindo49c75a82018-10-28 15:02:17 +0000150_Py_get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 PyTypeObject *tp;
153 PyObject *result;
154 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 result = PyList_New(0);
157 if (result == NULL)
158 return NULL;
159 for (tp = type_list; tp; tp = tp->tp_next) {
160 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
161 tp->tp_frees, tp->tp_maxalloc);
162 if (v == NULL) {
163 Py_DECREF(result);
164 return NULL;
165 }
166 if (PyList_Append(result, v) < 0) {
167 Py_DECREF(v);
168 Py_DECREF(result);
169 return NULL;
170 }
171 Py_DECREF(v);
172 }
173 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000174}
175
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000176void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000177_Py_inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
180 /* first time; insert in linked list */
181 if (tp->tp_next != NULL) /* sanity check */
Pablo Galindo49c75a82018-10-28 15:02:17 +0000182 Py_FatalError("XXX _Py_inc_count sanity check");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 if (type_list)
184 type_list->tp_prev = tp;
185 tp->tp_next = type_list;
186 /* Note that as of Python 2.2, heap-allocated type objects
187 * can go away, but this code requires that they stay alive
188 * until program exit. That's why we're careful with
189 * refcounts here. type_list gets a new reference to tp,
190 * while ownership of the reference type_list used to hold
191 * (if any) was transferred to tp->tp_next in the line above.
192 * tp is thus effectively immortal after this.
193 */
194 Py_INCREF(tp);
195 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000196#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 /* Also insert in the doubly-linked list of all objects,
198 * if not already there.
199 */
200 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000201#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 }
203 tp->tp_allocs++;
204 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
205 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000206}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000207
Pablo Galindo49c75a82018-10-28 15:02:17 +0000208void _Py_dec_count(PyTypeObject *tp)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 tp->tp_frees++;
211 if (unlist_types_without_objects &&
212 tp->tp_allocs == tp->tp_frees) {
213 /* unlink the type from type_list */
214 if (tp->tp_prev)
215 tp->tp_prev->tp_next = tp->tp_next;
216 else
217 type_list = tp->tp_next;
218 if (tp->tp_next)
219 tp->tp_next->tp_prev = tp->tp_prev;
220 tp->tp_next = tp->tp_prev = NULL;
221 Py_DECREF(tp);
222 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000223}
224
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000225#endif
226
Tim Peters7c321a82002-07-09 02:57:01 +0000227#ifdef Py_REF_DEBUG
228/* Log a fatal error; doesn't return. */
229void
Victor Stinner18618e652018-10-25 17:28:11 +0200230_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000231{
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100232 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200233 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000234}
235
236#endif /* Py_REF_DEBUG */
237
Thomas Heller1328b522004-04-22 17:23:49 +0000238void
239Py_IncRef(PyObject *o)
240{
241 Py_XINCREF(o);
242}
243
244void
245Py_DecRef(PyObject *o)
246{
247 Py_XDECREF(o);
248}
249
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000250PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000251PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (op == NULL)
254 return PyErr_NoMemory();
255 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
256 Py_TYPE(op) = tp;
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400257 if (PyType_GetFlags(tp) & Py_TPFLAGS_HEAPTYPE) {
258 Py_INCREF(tp);
259 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 _Py_NewReference(op);
261 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262}
263
Guido van Rossumb18618d2000-05-03 23:44:39 +0000264PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000265PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (op == NULL)
268 return (PyVarObject *) PyErr_NoMemory();
269 /* Any changes should be reflected in PyObject_INIT_VAR */
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400270 Py_SIZE(op) = size;
271 PyObject_Init((PyObject *)op, tp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000273}
274
275PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000276_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 PyObject *op;
279 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
280 if (op == NULL)
281 return PyErr_NoMemory();
282 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000283}
284
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000285PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000286_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 PyVarObject *op;
289 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
290 op = (PyVarObject *) PyObject_MALLOC(size);
291 if (op == NULL)
292 return (PyVarObject *)PyErr_NoMemory();
293 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000294}
295
Antoine Pitrou796564c2013-07-30 19:59:21 +0200296void
297PyObject_CallFinalizer(PyObject *self)
298{
299 PyTypeObject *tp = Py_TYPE(self);
300
301 /* The former could happen on heaptypes created from the C API, e.g.
302 PyType_FromSpec(). */
303 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
304 tp->tp_finalize == NULL)
305 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{
319 Py_ssize_t refcnt;
320
321 /* Temporarily resurrect the object. */
322 if (self->ob_refcnt != 0) {
323 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
324 "object with a non-zero refcount");
325 }
326 self->ob_refcnt = 1;
327
328 PyObject_CallFinalizer(self);
329
330 /* Undo the temporary resurrection; can't use DECREF here, it would
331 * cause a recursive call.
332 */
Victor Stinner24702042018-10-26 17:16:37 +0200333 _PyObject_ASSERT_WITH_MSG(self,
334 self->ob_refcnt > 0,
335 "refcount is too small");
Antoine Pitrou796564c2013-07-30 19:59:21 +0200336 if (--self->ob_refcnt == 0)
337 return 0; /* this is the normal path out */
338
339 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
340 * never happened.
341 */
342 refcnt = self->ob_refcnt;
343 _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
356 * undone.
357 */
358#ifdef COUNT_ALLOCS
359 --Py_TYPE(self)->tp_frees;
360 --Py_TYPE(self)->tp_allocs;
361#endif
362 return -1;
363}
364
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000365int
366PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (PyErr_CheckSignals())
370 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000371#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (PyOS_CheckStack()) {
373 PyErr_SetString(PyExc_MemoryError, "stack overflow");
374 return -1;
375 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000376#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 clearerr(fp); /* Clear any previous error condition */
378 if (op == NULL) {
379 Py_BEGIN_ALLOW_THREADS
380 fprintf(fp, "<nil>");
381 Py_END_ALLOW_THREADS
382 }
383 else {
Victor Stinner3ec9af72018-10-26 02:12:34 +0200384 if (op->ob_refcnt <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* XXX(twouters) cast refcount to long until %zd is
386 universally available */
387 Py_BEGIN_ALLOW_THREADS
388 fprintf(fp, "<refcnt %ld at %p>",
Zackery Spytz1a2252e2019-05-06 10:56:51 -0600389 (long)op->ob_refcnt, (void *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200391 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 else {
393 PyObject *s;
394 if (flags & Py_PRINT_RAW)
395 s = PyObject_Str(op);
396 else
397 s = PyObject_Repr(op);
398 if (s == NULL)
399 ret = -1;
400 else if (PyBytes_Check(s)) {
401 fwrite(PyBytes_AS_STRING(s), 1,
402 PyBytes_GET_SIZE(s), fp);
403 }
404 else if (PyUnicode_Check(s)) {
405 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200406 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600407 if (t == NULL) {
408 ret = -1;
409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 else {
411 fwrite(PyBytes_AS_STRING(t), 1,
412 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000413 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 }
415 }
416 else {
417 PyErr_Format(PyExc_TypeError,
418 "str() or repr() returned '%.100s'",
419 s->ob_type->tp_name);
420 ret = -1;
421 }
422 Py_XDECREF(s);
423 }
424 }
425 if (ret == 0) {
426 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300427 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 clearerr(fp);
429 ret = -1;
430 }
431 }
432 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433}
434
Guido van Rossum38938152006-08-21 23:36:26 +0000435/* For debugging convenience. Set a breakpoint here and call it from your DLL */
436void
Thomas Woutersb2137042007-02-01 18:02:27 +0000437_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000438{
439}
440
Neal Norwitz1a997502003-01-13 20:13:12 +0000441
Victor Stinner4c409be2019-04-11 13:01:15 +0200442/* Heuristic checking if the object memory is uninitialized or deallocated.
443 Rely on the debug hooks on Python memory allocators:
444 see _PyMem_IsPtrFreed().
Victor Stinner82af0b62018-10-23 17:39:40 +0200445
446 The function can be used to prevent segmentation fault on dereferencing
Victor Stinner4c409be2019-04-11 13:01:15 +0200447 pointers like 0xDDDDDDDDDDDDDDDD. */
Victor Stinner82af0b62018-10-23 17:39:40 +0200448int
449_PyObject_IsFreed(PyObject *op)
450{
Victor Stinner2b00db62019-04-11 11:33:27 +0200451 if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(op->ob_type)) {
Victor Stinner2cf5d322018-11-22 16:32:57 +0100452 return 1;
453 }
Victor Stinner2b00db62019-04-11 11:33:27 +0200454 /* ignore op->ob_ref: its value can have be modified
Victor Stinner82af0b62018-10-23 17:39:40 +0200455 by Py_INCREF() and Py_DECREF(). */
456#ifdef Py_TRACE_REFS
Victor Stinner2b00db62019-04-11 11:33:27 +0200457 if (_PyMem_IsPtrFreed(op->_ob_next) || _PyMem_IsPtrFreed(op->_ob_prev)) {
458 return 1;
459 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200460#endif
Victor Stinner2b00db62019-04-11 11:33:27 +0200461 return 0;
Victor Stinner82af0b62018-10-23 17:39:40 +0200462}
463
464
Barry Warsaw9bf16442001-01-23 16:24:35 +0000465/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000466void
467_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000468{
Victor Stinner82af0b62018-10-23 17:39:40 +0200469 if (op == NULL) {
470 fprintf(stderr, "<NULL object>\n");
471 fflush(stderr);
472 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200474
475 if (_PyObject_IsFreed(op)) {
476 /* It seems like the object memory has been freed:
477 don't access it to prevent a segmentation fault. */
Victor Stinner2b00db62019-04-11 11:33:27 +0200478 fprintf(stderr, "<Freed object>\n");
Victor Stinner2cf5d322018-11-22 16:32:57 +0100479 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200480 }
481
482 PyGILState_STATE gil;
483 PyObject *error_type, *error_value, *error_traceback;
484
485 fprintf(stderr, "object : ");
486 fflush(stderr);
487 gil = PyGILState_Ensure();
488
489 PyErr_Fetch(&error_type, &error_value, &error_traceback);
490 (void)PyObject_Print(op, stderr, 0);
491 fflush(stderr);
492 PyErr_Restore(error_type, error_value, error_traceback);
493
494 PyGILState_Release(gil);
495 /* XXX(twouters) cast refcount to long until %zd is
496 universally available */
497 fprintf(stderr, "\n"
498 "type : %s\n"
499 "refcount: %ld\n"
500 "address : %p\n",
501 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
502 (long)op->ob_refcnt,
Zackery Spytz1a2252e2019-05-06 10:56:51 -0600503 (void *)op);
Victor Stinner82af0b62018-10-23 17:39:40 +0200504 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000505}
Barry Warsaw903138f2001-01-23 16:33:18 +0000506
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000507PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000508PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyObject *res;
511 if (PyErr_CheckSignals())
512 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000513#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (PyOS_CheckStack()) {
515 PyErr_SetString(PyExc_MemoryError, "stack overflow");
516 return NULL;
517 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000518#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (v == NULL)
520 return PyUnicode_FromString("<NULL>");
521 if (Py_TYPE(v)->tp_repr == NULL)
522 return PyUnicode_FromFormat("<%s object at %p>",
523 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200524
525#ifdef Py_DEBUG
526 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100527 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000528 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200529 assert(!PyErr_Occurred());
530#endif
531
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200532 /* It is possible for a type to have a tp_repr representation that loops
533 infinitely. */
534 if (Py_EnterRecursiveCall(" while getting the repr of an object"))
535 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 res = (*v->ob_type->tp_repr)(v);
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200537 Py_LeaveRecursiveCall();
Victor Stinner0a54cf12011-12-01 03:22:44 +0100538 if (res == NULL)
539 return NULL;
540 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 PyErr_Format(PyExc_TypeError,
542 "__repr__ returned non-string (type %.200s)",
543 res->ob_type->tp_name);
544 Py_DECREF(res);
545 return NULL;
546 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100547#ifndef Py_DEBUG
548 if (PyUnicode_READY(res) < 0)
549 return NULL;
550#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552}
553
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000555PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyObject *res;
558 if (PyErr_CheckSignals())
559 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000560#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (PyOS_CheckStack()) {
562 PyErr_SetString(PyExc_MemoryError, "stack overflow");
563 return NULL;
564 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000565#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (v == NULL)
567 return PyUnicode_FromString("<NULL>");
568 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100569#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100570 if (PyUnicode_READY(v) < 0)
571 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100572#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 Py_INCREF(v);
574 return v;
575 }
576 if (Py_TYPE(v)->tp_str == NULL)
577 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000578
Victor Stinner33824f62013-08-26 14:05:19 +0200579#ifdef Py_DEBUG
580 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100581 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000582 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200583 assert(!PyErr_Occurred());
584#endif
585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 /* It is possible for a type to have a tp_str representation that loops
587 infinitely. */
588 if (Py_EnterRecursiveCall(" while getting the str of an object"))
589 return NULL;
590 res = (*Py_TYPE(v)->tp_str)(v);
591 Py_LeaveRecursiveCall();
592 if (res == NULL)
593 return NULL;
594 if (!PyUnicode_Check(res)) {
595 PyErr_Format(PyExc_TypeError,
596 "__str__ returned non-string (type %.200s)",
597 Py_TYPE(res)->tp_name);
598 Py_DECREF(res);
599 return NULL;
600 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100601#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100602 if (PyUnicode_READY(res) < 0)
603 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100604#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100605 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000607}
608
Georg Brandl559e5d72008-06-11 18:37:52 +0000609PyObject *
610PyObject_ASCII(PyObject *v)
611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 repr = PyObject_Repr(v);
615 if (repr == NULL)
616 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000617
Victor Stinneraf037572013-04-14 18:44:10 +0200618 if (PyUnicode_IS_ASCII(repr))
619 return repr;
620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200622 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 Py_DECREF(repr);
624 if (ascii == NULL)
625 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 res = PyUnicode_DecodeASCII(
628 PyBytes_AS_STRING(ascii),
629 PyBytes_GET_SIZE(ascii),
630 NULL);
631
632 Py_DECREF(ascii);
633 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000634}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000635
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000636PyObject *
637PyObject_Bytes(PyObject *v)
638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (v == NULL)
642 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (PyBytes_CheckExact(v)) {
645 Py_INCREF(v);
646 return v;
647 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000648
Benjamin Petersonce798522012-01-22 11:24:29 -0500649 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100651 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 Py_DECREF(func);
653 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000654 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000656 PyErr_Format(PyExc_TypeError,
657 "__bytes__ returned non-bytes (type %.200s)",
658 Py_TYPE(result)->tp_name);
659 Py_DECREF(result);
660 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 }
662 return result;
663 }
664 else if (PyErr_Occurred())
665 return NULL;
666 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000667}
668
Mark Dickinsonc008a172009-02-01 13:59:22 +0000669/* For Python 3.0.1 and later, the old three-way comparison has been
670 completely removed in favour of rich comparisons. PyObject_Compare() and
671 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000672 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000673 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000674
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000675 See (*) below for practical amendments.
676
Mark Dickinsonc008a172009-02-01 13:59:22 +0000677 tp_richcompare gets called with a first argument of the appropriate type
678 and a second object of an arbitrary type. We never do any kind of
679 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000680
Mark Dickinsonc008a172009-02-01 13:59:22 +0000681 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000682
683 NULL if an exception occurred
684 NotImplemented if the requested comparison is not implemented
685 any other false value if the requested comparison is false
686 any other true value if the requested comparison is true
687
688 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
689 NotImplemented.
690
691 (*) Practical amendments:
692
693 - If rich comparison returns NotImplemented, == and != are decided by
694 comparing the object pointer (i.e. falling back to the base object
695 implementation).
696
Guido van Rossuma4073002002-05-31 20:03:54 +0000697*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000698
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000699/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000700int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000701
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200702static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000703
704/* Perform a rich comparison, raising TypeError when the requested comparison
705 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000706static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000707do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 richcmpfunc f;
710 PyObject *res;
711 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (v->ob_type != w->ob_type &&
714 PyType_IsSubtype(w->ob_type, v->ob_type) &&
715 (f = w->ob_type->tp_richcompare) != NULL) {
716 checked_reverse_op = 1;
717 res = (*f)(w, v, _Py_SwappedOp[op]);
718 if (res != Py_NotImplemented)
719 return res;
720 Py_DECREF(res);
721 }
722 if ((f = v->ob_type->tp_richcompare) != NULL) {
723 res = (*f)(v, w, op);
724 if (res != Py_NotImplemented)
725 return res;
726 Py_DECREF(res);
727 }
728 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
729 res = (*f)(w, v, _Py_SwappedOp[op]);
730 if (res != Py_NotImplemented)
731 return res;
732 Py_DECREF(res);
733 }
734 /* If neither object implements it, provide a sensible default
735 for == and !=, but raise an exception for ordering. */
736 switch (op) {
737 case Py_EQ:
738 res = (v == w) ? Py_True : Py_False;
739 break;
740 case Py_NE:
741 res = (v != w) ? Py_True : Py_False;
742 break;
743 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyErr_Format(PyExc_TypeError,
Victor Stinner91108f02015-10-14 18:25:31 +0200745 "'%s' not supported between instances of '%.100s' and '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 opstrings[op],
Victor Stinner91108f02015-10-14 18:25:31 +0200747 v->ob_type->tp_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 w->ob_type->tp_name);
749 return NULL;
750 }
751 Py_INCREF(res);
752 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000753}
754
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000755/* Perform a rich comparison with object result. This wraps do_richcompare()
756 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000757
Guido van Rossume797ec12001-01-17 15:24:28 +0000758PyObject *
759PyObject_RichCompare(PyObject *v, PyObject *w, int op)
760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 assert(Py_LT <= op && op <= Py_GE);
764 if (v == NULL || w == NULL) {
765 if (!PyErr_Occurred())
766 PyErr_BadInternalCall();
767 return NULL;
768 }
769 if (Py_EnterRecursiveCall(" in comparison"))
770 return NULL;
771 res = do_richcompare(v, w, op);
772 Py_LeaveRecursiveCall();
773 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000774}
775
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000776/* Perform a rich comparison with integer result. This wraps
777 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000778int
779PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyObject *res;
782 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Quick result when objects are the same.
785 Guarantees that identity implies equality. */
786 if (v == w) {
787 if (op == Py_EQ)
788 return 1;
789 else if (op == Py_NE)
790 return 0;
791 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 res = PyObject_RichCompare(v, w, op);
794 if (res == NULL)
795 return -1;
796 if (PyBool_Check(res))
797 ok = (res == Py_True);
798 else
799 ok = PyObject_IsTrue(res);
800 Py_DECREF(res);
801 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000802}
Fred Drake13634cf2000-06-29 19:17:04 +0000803
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100804Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000805PyObject_HashNotImplemented(PyObject *v)
806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
808 Py_TYPE(v)->tp_name);
809 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000810}
Fred Drake13634cf2000-06-29 19:17:04 +0000811
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000812Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000813PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 PyTypeObject *tp = Py_TYPE(v);
816 if (tp->tp_hash != NULL)
817 return (*tp->tp_hash)(v);
818 /* To keep to the general practice that inheriting
819 * solely from object in C code should work without
820 * an explicit call to PyType_Ready, we implicitly call
821 * PyType_Ready here and then check the tp_hash slot again
822 */
823 if (tp->tp_dict == NULL) {
824 if (PyType_Ready(tp) < 0)
825 return -1;
826 if (tp->tp_hash != NULL)
827 return (*tp->tp_hash)(v);
828 }
829 /* Otherwise, the object can't be hashed */
830 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000831}
832
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000833PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000834PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (Py_TYPE(v)->tp_getattr != NULL)
839 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900840 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (w == NULL)
842 return NULL;
843 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100844 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000846}
847
848int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000849PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyObject *res = PyObject_GetAttrString(v, name);
852 if (res != NULL) {
853 Py_DECREF(res);
854 return 1;
855 }
856 PyErr_Clear();
857 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000858}
859
860int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000861PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 PyObject *s;
864 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (Py_TYPE(v)->tp_setattr != NULL)
867 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
868 s = PyUnicode_InternFromString(name);
869 if (s == NULL)
870 return -1;
871 res = PyObject_SetAttr(v, s, w);
872 Py_XDECREF(s);
873 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000874}
875
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500876int
877_PyObject_IsAbstract(PyObject *obj)
878{
879 int res;
880 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500881
882 if (obj == NULL)
883 return 0;
884
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200885 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
886 if (res > 0) {
887 res = PyObject_IsTrue(isabstract);
888 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500889 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500890 return res;
891}
892
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000893PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200894_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
895{
896 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100897 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200898 if (!oname)
899 return NULL;
900 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200901 return result;
902}
903
904int
905_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
906{
907 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100908 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200909 if (!oname)
910 return -1;
911 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200912 return result;
913}
914
915int
916_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
917{
918 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100919 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200920 if (!oname)
921 return -1;
922 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200923 return result;
924}
925
926PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000927PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (!PyUnicode_Check(name)) {
932 PyErr_Format(PyExc_TypeError,
933 "attribute name must be string, not '%.200s'",
934 name->ob_type->tp_name);
935 return NULL;
936 }
937 if (tp->tp_getattro != NULL)
938 return (*tp->tp_getattro)(v, name);
939 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200940 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (name_str == NULL)
942 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200943 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 }
945 PyErr_Format(PyExc_AttributeError,
946 "'%.50s' object has no attribute '%U'",
947 tp->tp_name, name);
948 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000949}
950
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200951int
952_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900953{
954 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900955
956 if (!PyUnicode_Check(name)) {
957 PyErr_Format(PyExc_TypeError,
958 "attribute name must be string, not '%.200s'",
959 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200960 *result = NULL;
961 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900962 }
963
964 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200965 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
966 if (*result != NULL) {
967 return 1;
968 }
969 if (PyErr_Occurred()) {
970 return -1;
971 }
972 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900973 }
974 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200975 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900976 }
977 else if (tp->tp_getattr != NULL) {
978 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200979 if (name_str == NULL) {
980 *result = NULL;
981 return -1;
982 }
983 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900984 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900985 else {
986 *result = NULL;
987 return 0;
988 }
989
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200990 if (*result != NULL) {
991 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900992 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200993 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
994 return -1;
995 }
996 PyErr_Clear();
997 return 0;
998}
999
1000int
1001_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
1002{
1003 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
1004 if (!oname) {
1005 *result = NULL;
1006 return -1;
1007 }
1008 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +09001009}
1010
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001011int
Fred Drake100814d2000-07-09 15:48:49 +00001012PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001013{
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001014 PyObject *res;
1015 if (_PyObject_LookupAttr(v, name, &res) < 0) {
1016 PyErr_Clear();
1017 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001019 if (res == NULL) {
1020 return 0;
1021 }
1022 Py_DECREF(res);
1023 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001024}
1025
1026int
Fred Drake100814d2000-07-09 15:48:49 +00001027PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyTypeObject *tp = Py_TYPE(v);
1030 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 if (!PyUnicode_Check(name)) {
1033 PyErr_Format(PyExc_TypeError,
1034 "attribute name must be string, not '%.200s'",
1035 name->ob_type->tp_name);
1036 return -1;
1037 }
1038 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyUnicode_InternInPlace(&name);
1041 if (tp->tp_setattro != NULL) {
1042 err = (*tp->tp_setattro)(v, name, value);
1043 Py_DECREF(name);
1044 return err;
1045 }
1046 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001047 const char *name_str = PyUnicode_AsUTF8(name);
Zackery Spytze0dcb852019-04-28 06:58:52 -06001048 if (name_str == NULL) {
1049 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 return -1;
Zackery Spytze0dcb852019-04-28 06:58:52 -06001051 }
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001052 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 Py_DECREF(name);
1054 return err;
1055 }
1056 Py_DECREF(name);
Victor Stinner24702042018-10-26 17:16:37 +02001057 _PyObject_ASSERT(name, name->ob_refcnt >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1059 PyErr_Format(PyExc_TypeError,
1060 "'%.100s' object has no attributes "
1061 "(%s .%U)",
1062 tp->tp_name,
1063 value==NULL ? "del" : "assign to",
1064 name);
1065 else
1066 PyErr_Format(PyExc_TypeError,
1067 "'%.100s' object has only read-only attributes "
1068 "(%s .%U)",
1069 tp->tp_name,
1070 value==NULL ? "del" : "assign to",
1071 name);
1072 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001073}
1074
1075/* Helper to get a pointer to an object's __dict__ slot, if any */
1076
1077PyObject **
1078_PyObject_GetDictPtr(PyObject *obj)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 Py_ssize_t dictoffset;
1081 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 dictoffset = tp->tp_dictoffset;
1084 if (dictoffset == 0)
1085 return NULL;
1086 if (dictoffset < 0) {
1087 Py_ssize_t tsize;
1088 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 tsize = ((PyVarObject *)obj)->ob_size;
1091 if (tsize < 0)
1092 tsize = -tsize;
1093 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001096 _PyObject_ASSERT(obj, dictoffset > 0);
1097 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 }
1099 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001100}
1101
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001103PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 Py_INCREF(obj);
1106 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001107}
1108
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001109/* Helper used when the __next__ method is removed from a type:
1110 tp_iternext is never NULL and can be safely called without checking
1111 on every iteration.
1112 */
1113
1114PyObject *
1115_PyObject_NextNotImplemented(PyObject *self)
1116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyErr_Format(PyExc_TypeError,
1118 "'%.200s' object is not iterable",
1119 Py_TYPE(self)->tp_name);
1120 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001121}
1122
Yury Selivanovf2392132016-12-13 19:03:51 -05001123
1124/* Specialized version of _PyObject_GenericGetAttrWithDict
1125 specifically for the LOAD_METHOD opcode.
1126
1127 Return 1 if a method is found, 0 if it's a regular attribute
1128 from __dict__ or something returned by using a descriptor
1129 protocol.
1130
1131 `method` will point to the resolved attribute or NULL. In the
1132 latter case, an error will be set.
1133*/
1134int
1135_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1136{
1137 PyTypeObject *tp = Py_TYPE(obj);
1138 PyObject *descr;
1139 descrgetfunc f = NULL;
1140 PyObject **dictptr, *dict;
1141 PyObject *attr;
1142 int meth_found = 0;
1143
1144 assert(*method == NULL);
1145
1146 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1147 || !PyUnicode_Check(name)) {
1148 *method = PyObject_GetAttr(obj, name);
1149 return 0;
1150 }
1151
1152 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1153 return 0;
1154
1155 descr = _PyType_Lookup(tp, name);
1156 if (descr != NULL) {
1157 Py_INCREF(descr);
INADA Naoki5566bbb2017-02-03 07:43:03 +09001158 if (PyFunction_Check(descr) ||
1159 (Py_TYPE(descr) == &PyMethodDescr_Type)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001160 meth_found = 1;
1161 } else {
1162 f = descr->ob_type->tp_descr_get;
1163 if (f != NULL && PyDescr_IsData(descr)) {
1164 *method = f(descr, obj, (PyObject *)obj->ob_type);
1165 Py_DECREF(descr);
1166 return 0;
1167 }
1168 }
1169 }
1170
1171 dictptr = _PyObject_GetDictPtr(obj);
1172 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1173 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001174 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001175 if (attr != NULL) {
1176 Py_INCREF(attr);
1177 *method = attr;
1178 Py_DECREF(dict);
1179 Py_XDECREF(descr);
1180 return 0;
1181 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001182 else {
1183 Py_DECREF(dict);
1184 if (PyErr_Occurred()) {
1185 Py_XDECREF(descr);
1186 return 0;
1187 }
1188 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001189 }
1190
1191 if (meth_found) {
1192 *method = descr;
1193 return 1;
1194 }
1195
1196 if (f != NULL) {
1197 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1198 Py_DECREF(descr);
1199 return 0;
1200 }
1201
1202 if (descr != NULL) {
1203 *method = descr;
1204 return 0;
1205 }
1206
1207 PyErr_Format(PyExc_AttributeError,
1208 "'%.50s' object has no attribute '%U'",
1209 tp->tp_name, name);
1210 return 0;
1211}
1212
1213/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001214
Raymond Hettinger01538262003-03-17 08:24:35 +00001215PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001216_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1217 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218{
Yury Selivanovf2392132016-12-13 19:03:51 -05001219 /* Make sure the logic of _PyObject_GetMethod is in sync with
1220 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001221
1222 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001223 */
1224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyTypeObject *tp = Py_TYPE(obj);
1226 PyObject *descr = NULL;
1227 PyObject *res = NULL;
1228 descrgetfunc f;
1229 Py_ssize_t dictoffset;
1230 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (!PyUnicode_Check(name)){
1233 PyErr_Format(PyExc_TypeError,
1234 "attribute name must be string, not '%.200s'",
1235 name->ob_type->tp_name);
1236 return NULL;
1237 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001238 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (tp->tp_dict == NULL) {
1241 if (PyType_Ready(tp) < 0)
1242 goto done;
1243 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 f = NULL;
1248 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001249 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 f = descr->ob_type->tp_descr_get;
1251 if (f != NULL && PyDescr_IsData(descr)) {
1252 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001253 if (res == NULL && suppress &&
1254 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1255 PyErr_Clear();
1256 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 goto done;
1258 }
1259 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001260
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001261 if (dict == NULL) {
1262 /* Inline _PyObject_GetDictPtr */
1263 dictoffset = tp->tp_dictoffset;
1264 if (dictoffset != 0) {
1265 if (dictoffset < 0) {
1266 Py_ssize_t tsize;
1267 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001268
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001269 tsize = ((PyVarObject *)obj)->ob_size;
1270 if (tsize < 0)
1271 tsize = -tsize;
1272 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001273 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001274
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001275 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001276 _PyObject_ASSERT(obj, dictoffset > 0);
1277 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001279 dictptr = (PyObject **) ((char *)obj + dictoffset);
1280 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 }
1282 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001283 if (dict != NULL) {
1284 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001285 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001286 if (res != NULL) {
1287 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001288 Py_DECREF(dict);
1289 goto done;
1290 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001291 else {
1292 Py_DECREF(dict);
1293 if (PyErr_Occurred()) {
1294 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1295 PyErr_Clear();
1296 }
1297 else {
1298 goto done;
1299 }
1300 }
1301 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001302 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 if (f != NULL) {
1305 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001306 if (res == NULL && suppress &&
1307 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1308 PyErr_Clear();
1309 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 goto done;
1311 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (descr != NULL) {
1314 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001315 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 goto done;
1317 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001318
INADA Naoki378edee2018-01-16 20:52:41 +09001319 if (!suppress) {
1320 PyErr_Format(PyExc_AttributeError,
1321 "'%.50s' object has no attribute '%U'",
1322 tp->tp_name, name);
1323 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001324 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001325 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 Py_DECREF(name);
1327 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001328}
1329
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001330PyObject *
1331PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1332{
INADA Naoki378edee2018-01-16 20:52:41 +09001333 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001334}
1335
Tim Peters6d6c1a32001-08-02 04:15:00 +00001336int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001337_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1338 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 PyTypeObject *tp = Py_TYPE(obj);
1341 PyObject *descr;
1342 descrsetfunc f;
1343 PyObject **dictptr;
1344 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (!PyUnicode_Check(name)){
1347 PyErr_Format(PyExc_TypeError,
1348 "attribute name must be string, not '%.200s'",
1349 name->ob_type->tp_name);
1350 return -1;
1351 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001352
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001353 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1354 return -1;
1355
1356 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001361 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001363 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 res = f(descr, obj, value);
1365 goto done;
1366 }
1367 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001368
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001369 if (dict == NULL) {
1370 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001371 if (dictptr == NULL) {
1372 if (descr == NULL) {
1373 PyErr_Format(PyExc_AttributeError,
1374 "'%.100s' object has no attribute '%U'",
1375 tp->tp_name, name);
1376 }
1377 else {
1378 PyErr_Format(PyExc_AttributeError,
1379 "'%.50s' object attribute '%U' is read-only",
1380 tp->tp_name, name);
1381 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001382 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001384 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001385 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001386 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001387 Py_INCREF(dict);
1388 if (value == NULL)
1389 res = PyDict_DelItem(dict, name);
1390 else
1391 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001392 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001394 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1395 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001396
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001397 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001398 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_DECREF(name);
1400 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001401}
1402
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001403int
1404PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1405{
1406 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1407}
1408
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001409int
1410PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1411{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001412 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001413 if (dictptr == NULL) {
1414 PyErr_SetString(PyExc_AttributeError,
1415 "This object has no __dict__");
1416 return -1;
1417 }
1418 if (value == NULL) {
1419 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1420 return -1;
1421 }
1422 if (!PyDict_Check(value)) {
1423 PyErr_Format(PyExc_TypeError,
1424 "__dict__ must be set to a dictionary, "
1425 "not a '%.200s'", Py_TYPE(value)->tp_name);
1426 return -1;
1427 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001428 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001429 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001430 return 0;
1431}
1432
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001433
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001434/* Test a value used as condition, e.g., in a for or if statement.
1435 Return -1 if an error occurred */
1436
1437int
Fred Drake100814d2000-07-09 15:48:49 +00001438PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 Py_ssize_t res;
1441 if (v == Py_True)
1442 return 1;
1443 if (v == Py_False)
1444 return 0;
1445 if (v == Py_None)
1446 return 0;
1447 else if (v->ob_type->tp_as_number != NULL &&
1448 v->ob_type->tp_as_number->nb_bool != NULL)
1449 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1450 else if (v->ob_type->tp_as_mapping != NULL &&
1451 v->ob_type->tp_as_mapping->mp_length != NULL)
1452 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1453 else if (v->ob_type->tp_as_sequence != NULL &&
1454 v->ob_type->tp_as_sequence->sq_length != NULL)
1455 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1456 else
1457 return 1;
1458 /* if it is negative, it should be either -1 or -2 */
1459 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001460}
1461
Tim Peters803526b2002-07-07 05:13:56 +00001462/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001463 Return -1 if an error occurred */
1464
1465int
Fred Drake100814d2000-07-09 15:48:49 +00001466PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 int res;
1469 res = PyObject_IsTrue(v);
1470 if (res < 0)
1471 return res;
1472 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001473}
1474
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001475/* Test whether an object can be called */
1476
1477int
Fred Drake100814d2000-07-09 15:48:49 +00001478PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (x == NULL)
1481 return 0;
1482 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001483}
1484
Tim Peters7eea37e2001-09-04 22:08:56 +00001485
Georg Brandle32b4222007-03-10 22:13:27 +00001486/* Helper for PyObject_Dir without arguments: returns the local scope. */
1487static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001488_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001491 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001492
Victor Stinner41bb43a2013-10-29 01:19:37 +01001493 locals = PyEval_GetLocals();
1494 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 names = PyMapping_Keys(locals);
1498 if (!names)
1499 return NULL;
1500 if (!PyList_Check(names)) {
1501 PyErr_Format(PyExc_TypeError,
1502 "dir(): expected keys() of locals to be a list, "
1503 "not '%.200s'", Py_TYPE(names)->tp_name);
1504 Py_DECREF(names);
1505 return NULL;
1506 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001507 if (PyList_Sort(names)) {
1508 Py_DECREF(names);
1509 return NULL;
1510 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 /* the locals don't need to be DECREF'd */
1512 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001513}
1514
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001515/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001516static PyObject *
1517_dir_object(PyObject *obj)
1518{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001519 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001520 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001521
Victor Stinner24702042018-10-26 17:16:37 +02001522 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001524 if (!PyErr_Occurred())
1525 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1526 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001528 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001529 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001530 Py_DECREF(dirfunc);
1531 if (result == NULL)
1532 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001533 /* return sorted(result) */
1534 sorted = PySequence_List(result);
1535 Py_DECREF(result);
1536 if (sorted == NULL)
1537 return NULL;
1538 if (PyList_Sort(sorted)) {
1539 Py_DECREF(sorted);
1540 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001542 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001543}
1544
1545/* Implementation of dir() -- if obj is NULL, returns the names in the current
1546 (local) scope. Otherwise, performs introspection of the object: returns a
1547 sorted list of attribute names (supposedly) accessible from the object
1548*/
1549PyObject *
1550PyObject_Dir(PyObject *obj)
1551{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001552 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001553}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001554
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001555/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001556None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001557There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001558so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001559*/
1560
Guido van Rossum0c182a11992-03-27 17:26:13 +00001561/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001562static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001563none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001566}
1567
Barry Warsaw9bf16442001-01-23 16:24:35 +00001568/* ARGUSED */
1569static void
Tim Peters803526b2002-07-07 05:13:56 +00001570none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 /* This should never get called, but we also don't want to SEGV if
1573 * we accidentally decref None out of existence.
1574 */
1575 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001576}
1577
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001578static PyObject *
1579none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1580{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001581 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001582 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1583 return NULL;
1584 }
1585 Py_RETURN_NONE;
1586}
1587
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001588static int
1589none_bool(PyObject *v)
1590{
1591 return 0;
1592}
1593
1594static PyNumberMethods none_as_number = {
1595 0, /* nb_add */
1596 0, /* nb_subtract */
1597 0, /* nb_multiply */
1598 0, /* nb_remainder */
1599 0, /* nb_divmod */
1600 0, /* nb_power */
1601 0, /* nb_negative */
1602 0, /* nb_positive */
1603 0, /* nb_absolute */
1604 (inquiry)none_bool, /* nb_bool */
1605 0, /* nb_invert */
1606 0, /* nb_lshift */
1607 0, /* nb_rshift */
1608 0, /* nb_and */
1609 0, /* nb_xor */
1610 0, /* nb_or */
1611 0, /* nb_int */
1612 0, /* nb_reserved */
1613 0, /* nb_float */
1614 0, /* nb_inplace_add */
1615 0, /* nb_inplace_subtract */
1616 0, /* nb_inplace_multiply */
1617 0, /* nb_inplace_remainder */
1618 0, /* nb_inplace_power */
1619 0, /* nb_inplace_lshift */
1620 0, /* nb_inplace_rshift */
1621 0, /* nb_inplace_and */
1622 0, /* nb_inplace_xor */
1623 0, /* nb_inplace_or */
1624 0, /* nb_floor_divide */
1625 0, /* nb_true_divide */
1626 0, /* nb_inplace_floor_divide */
1627 0, /* nb_inplace_true_divide */
1628 0, /* nb_index */
1629};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001630
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001631PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1633 "NoneType",
1634 0,
1635 0,
1636 none_dealloc, /*tp_dealloc*/ /*never called*/
1637 0, /*tp_print*/
1638 0, /*tp_getattr*/
1639 0, /*tp_setattr*/
1640 0, /*tp_reserved*/
1641 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001642 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 0, /*tp_as_sequence*/
1644 0, /*tp_as_mapping*/
1645 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001646 0, /*tp_call */
1647 0, /*tp_str */
1648 0, /*tp_getattro */
1649 0, /*tp_setattro */
1650 0, /*tp_as_buffer */
1651 Py_TPFLAGS_DEFAULT, /*tp_flags */
1652 0, /*tp_doc */
1653 0, /*tp_traverse */
1654 0, /*tp_clear */
1655 0, /*tp_richcompare */
1656 0, /*tp_weaklistoffset */
1657 0, /*tp_iter */
1658 0, /*tp_iternext */
1659 0, /*tp_methods */
1660 0, /*tp_members */
1661 0, /*tp_getset */
1662 0, /*tp_base */
1663 0, /*tp_dict */
1664 0, /*tp_descr_get */
1665 0, /*tp_descr_set */
1666 0, /*tp_dictoffset */
1667 0, /*tp_init */
1668 0, /*tp_alloc */
1669 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001670};
1671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001672PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001673 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001674 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001675};
1676
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001677/* NotImplemented is an object that can be used to signal that an
1678 operation is not implemented for the given type combination. */
1679
1680static PyObject *
1681NotImplemented_repr(PyObject *op)
1682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001684}
1685
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001686static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301687NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001688{
1689 return PyUnicode_FromString("NotImplemented");
1690}
1691
1692static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301693 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001694 {NULL, NULL}
1695};
1696
1697static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001698notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1699{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001700 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001701 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1702 return NULL;
1703 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001704 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001705}
1706
Armin Ronacher226b1db2012-10-06 14:28:58 +02001707static void
1708notimplemented_dealloc(PyObject* ignore)
1709{
1710 /* This should never get called, but we also don't want to SEGV if
1711 * we accidentally decref NotImplemented out of existence.
1712 */
1713 Py_FatalError("deallocating NotImplemented");
1714}
1715
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001716PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1718 "NotImplementedType",
1719 0,
1720 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001721 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 0, /*tp_print*/
1723 0, /*tp_getattr*/
1724 0, /*tp_setattr*/
1725 0, /*tp_reserved*/
1726 NotImplemented_repr, /*tp_repr*/
1727 0, /*tp_as_number*/
1728 0, /*tp_as_sequence*/
1729 0, /*tp_as_mapping*/
1730 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001731 0, /*tp_call */
1732 0, /*tp_str */
1733 0, /*tp_getattro */
1734 0, /*tp_setattro */
1735 0, /*tp_as_buffer */
1736 Py_TPFLAGS_DEFAULT, /*tp_flags */
1737 0, /*tp_doc */
1738 0, /*tp_traverse */
1739 0, /*tp_clear */
1740 0, /*tp_richcompare */
1741 0, /*tp_weaklistoffset */
1742 0, /*tp_iter */
1743 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001744 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001745 0, /*tp_members */
1746 0, /*tp_getset */
1747 0, /*tp_base */
1748 0, /*tp_dict */
1749 0, /*tp_descr_get */
1750 0, /*tp_descr_set */
1751 0, /*tp_dictoffset */
1752 0, /*tp_init */
1753 0, /*tp_alloc */
1754 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001755};
1756
1757PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001759 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001760};
1761
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001762_PyInitError
Victor Stinnerab672812019-01-23 15:04:40 +01001763_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001764{
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001765#define INIT_TYPE(TYPE, NAME) \
1766 do { \
1767 if (PyType_Ready(TYPE) < 0) { \
1768 return _Py_INIT_ERR("Can't initialize " NAME " type"); \
1769 } \
1770 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001771
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001772 INIT_TYPE(&PyBaseObject_Type, "object");
1773 INIT_TYPE(&PyType_Type, "type");
1774 INIT_TYPE(&_PyWeakref_RefType, "weakref");
1775 INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
1776 INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
1777 INIT_TYPE(&PyLong_Type, "int");
1778 INIT_TYPE(&PyBool_Type, "bool");
1779 INIT_TYPE(&PyByteArray_Type, "bytearray");
1780 INIT_TYPE(&PyBytes_Type, "str");
1781 INIT_TYPE(&PyList_Type, "list");
1782 INIT_TYPE(&_PyNone_Type, "None");
1783 INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
1784 INIT_TYPE(&PyTraceBack_Type, "traceback");
1785 INIT_TYPE(&PySuper_Type, "super");
1786 INIT_TYPE(&PyRange_Type, "range");
1787 INIT_TYPE(&PyDict_Type, "dict");
1788 INIT_TYPE(&PyDictKeys_Type, "dict keys");
1789 INIT_TYPE(&PyDictValues_Type, "dict values");
1790 INIT_TYPE(&PyDictItems_Type, "dict items");
1791 INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
1792 INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
1793 INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
1794 INIT_TYPE(&PyODict_Type, "OrderedDict");
1795 INIT_TYPE(&PyODictKeys_Type, "odict_keys");
1796 INIT_TYPE(&PyODictItems_Type, "odict_items");
1797 INIT_TYPE(&PyODictValues_Type, "odict_values");
1798 INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
1799 INIT_TYPE(&PySet_Type, "set");
1800 INIT_TYPE(&PyUnicode_Type, "str");
1801 INIT_TYPE(&PySlice_Type, "slice");
1802 INIT_TYPE(&PyStaticMethod_Type, "static method");
1803 INIT_TYPE(&PyComplex_Type, "complex");
1804 INIT_TYPE(&PyFloat_Type, "float");
1805 INIT_TYPE(&PyFrozenSet_Type, "frozenset");
1806 INIT_TYPE(&PyProperty_Type, "property");
1807 INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
1808 INIT_TYPE(&PyMemoryView_Type, "memoryview");
1809 INIT_TYPE(&PyTuple_Type, "tuple");
1810 INIT_TYPE(&PyEnum_Type, "enumerate");
1811 INIT_TYPE(&PyReversed_Type, "reversed");
1812 INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
1813 INIT_TYPE(&PyCode_Type, "code");
1814 INIT_TYPE(&PyFrame_Type, "frame");
1815 INIT_TYPE(&PyCFunction_Type, "builtin function");
1816 INIT_TYPE(&PyMethod_Type, "method");
1817 INIT_TYPE(&PyFunction_Type, "function");
1818 INIT_TYPE(&PyDictProxy_Type, "dict proxy");
1819 INIT_TYPE(&PyGen_Type, "generator");
1820 INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
1821 INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
1822 INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
1823 INIT_TYPE(&PyEllipsis_Type, "ellipsis");
1824 INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
1825 INIT_TYPE(&_PyNamespace_Type, "namespace");
1826 INIT_TYPE(&PyCapsule_Type, "capsule");
1827 INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
1828 INIT_TYPE(&PyCell_Type, "cell");
1829 INIT_TYPE(&PyInstanceMethod_Type, "instance method");
1830 INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
1831 INIT_TYPE(&PyMethodDescr_Type, "method descr");
1832 INIT_TYPE(&PyCallIter_Type, "call iter");
1833 INIT_TYPE(&PySeqIter_Type, "sequence iterator");
1834 INIT_TYPE(&PyCoro_Type, "coroutine");
1835 INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
Eric Snowc11183c2019-03-15 16:35:46 -06001836 INIT_TYPE(&_PyInterpreterID_Type, "interpreter ID");
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001837 return _Py_INIT_OK();
Guido van Rossumba21a492001-08-16 08:17:26 +00001838
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001839#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001840}
1841
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842
Guido van Rossum84a90321996-05-22 16:34:47 +00001843#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001844
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001845void
Fred Drake100814d2000-07-09 15:48:49 +00001846_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001847{
Victor Stinner9e00e802018-10-25 13:31:16 +02001848 if (_Py_tracemalloc_config.tracing) {
1849 _PyTraceMalloc_NewReference(op);
1850 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 _Py_INC_REFTOTAL;
1852 op->ob_refcnt = 1;
1853 _Py_AddToAllObjects(op, 1);
1854 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001855}
1856
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001857void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001858_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001859{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001860#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001861 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001862#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 if (op->ob_refcnt < 0)
1864 Py_FatalError("UNREF negative refcnt");
1865 if (op == &refchain ||
1866 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1867 fprintf(stderr, "* ob\n");
1868 _PyObject_Dump(op);
1869 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1870 _PyObject_Dump(op->_ob_prev->_ob_next);
1871 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1872 _PyObject_Dump(op->_ob_next->_ob_prev);
1873 Py_FatalError("UNREF invalid object");
1874 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001875#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1877 if (p == op)
1878 break;
1879 }
1880 if (p == &refchain) /* Not found */
1881 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001882#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 op->_ob_next->_ob_prev = op->_ob_prev;
1884 op->_ob_prev->_ob_next = op->_ob_next;
1885 op->_ob_next = op->_ob_prev = NULL;
1886 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001887}
1888
Tim Peters269b2a62003-04-17 19:52:29 +00001889/* Print all live objects. Because PyObject_Print is called, the
1890 * interpreter must be in a healthy state.
1891 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001892void
Fred Drake100814d2000-07-09 15:48:49 +00001893_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 PyObject *op;
1896 fprintf(fp, "Remaining objects:\n");
1897 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001898 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", (void *)op, op->ob_refcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (PyObject_Print(op, fp, 0) != 0)
1900 PyErr_Clear();
1901 putc('\n', fp);
1902 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001903}
1904
Tim Peters269b2a62003-04-17 19:52:29 +00001905/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1906 * doesn't make any calls to the Python C API, so is always safe to call.
1907 */
1908void
1909_Py_PrintReferenceAddresses(FILE *fp)
1910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 PyObject *op;
1912 fprintf(fp, "Remaining object addresses:\n");
1913 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001914 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", (void *)op,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001916}
1917
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001918PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001919_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 int i, n;
1922 PyObject *t = NULL;
1923 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1926 return NULL;
1927 op = refchain._ob_next;
1928 res = PyList_New(0);
1929 if (res == NULL)
1930 return NULL;
1931 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1932 while (op == self || op == args || op == res || op == t ||
1933 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1934 op = op->_ob_next;
1935 if (op == &refchain)
1936 return res;
1937 }
1938 if (PyList_Append(res, op) < 0) {
1939 Py_DECREF(res);
1940 return NULL;
1941 }
1942 op = op->_ob_next;
1943 }
1944 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001945}
1946
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001947#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001948
Benjamin Petersonb173f782009-05-05 22:31:58 +00001949
Guido van Rossum84a90321996-05-22 16:34:47 +00001950/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001951Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001952
1953
David Malcolm49526f42012-06-22 14:55:41 -04001954void
1955_PyObject_DebugTypeStats(FILE *out)
1956{
1957 _PyCFunction_DebugMallocStats(out);
1958 _PyDict_DebugMallocStats(out);
1959 _PyFloat_DebugMallocStats(out);
1960 _PyFrame_DebugMallocStats(out);
1961 _PyList_DebugMallocStats(out);
1962 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001963 _PyTuple_DebugMallocStats(out);
1964}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001965
Guido van Rossum86610361998-04-10 22:32:46 +00001966/* These methods are used to control infinite recursion in repr, str, print,
1967 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00001968 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00001969 Py_ReprLeave() to avoid infinite recursion.
1970
1971 Py_ReprEnter() returns 0 the first time it is called for a particular
1972 object and 1 every time thereafter. It returns -1 if an exception
1973 occurred. Py_ReprLeave() has no return value.
1974
1975 See dictobject.c and listobject.c for examples of use.
1976*/
1977
Guido van Rossum86610361998-04-10 22:32:46 +00001978int
Fred Drake100814d2000-07-09 15:48:49 +00001979Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject *dict;
1982 PyObject *list;
1983 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02001986 /* Ignore a missing thread-state, so that this function can be called
1987 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (dict == NULL)
1989 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001990 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001992 if (PyErr_Occurred()) {
1993 return -1;
1994 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 list = PyList_New(0);
1996 if (list == NULL)
1997 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001998 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 return -1;
2000 Py_DECREF(list);
2001 }
2002 i = PyList_GET_SIZE(list);
2003 while (--i >= 0) {
2004 if (PyList_GET_ITEM(list, i) == obj)
2005 return 1;
2006 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002007 if (PyList_Append(list, obj) < 0)
2008 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002010}
2011
2012void
Fred Drake100814d2000-07-09 15:48:49 +00002013Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 PyObject *dict;
2016 PyObject *list;
2017 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002018 PyObject *error_type, *error_value, *error_traceback;
2019
2020 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 dict = PyThreadState_GetDict();
2023 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002024 goto finally;
2025
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002026 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002028 goto finally;
2029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 i = PyList_GET_SIZE(list);
2031 /* Count backwards because we always expect obj to be list[-1] */
2032 while (--i >= 0) {
2033 if (PyList_GET_ITEM(list, i) == obj) {
2034 PyList_SetSlice(list, i, i + 1, NULL);
2035 break;
2036 }
2037 }
Victor Stinner1b634932013-07-16 22:24:44 +02002038
2039finally:
2040 /* ignore exceptions because there is no way to report them. */
2041 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002042}
Guido van Rossumd724b232000-03-13 16:01:29 +00002043
Tim Peters803526b2002-07-07 05:13:56 +00002044/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002045
Tim Peters803526b2002-07-07 05:13:56 +00002046/* Add op to the _PyTrash_delete_later list. Called when the current
2047 * call-stack depth gets large. op must be a currently untracked gc'ed
2048 * object, with refcount 0. Py_DECREF must already have been called on it.
2049 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002050void
Fred Drake100814d2000-07-09 15:48:49 +00002051_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002052{
Victor Stinner24702042018-10-26 17:16:37 +02002053 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2054 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2055 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002056 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002057 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002058}
2059
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002060/* The equivalent API, using per-thread state recursion info */
2061void
2062_PyTrash_thread_deposit_object(PyObject *op)
2063{
Victor Stinner50b48572018-11-01 01:51:40 +01002064 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002065 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2066 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2067 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002068 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002069 tstate->trash_delete_later = op;
2070}
2071
Tim Peters803526b2002-07-07 05:13:56 +00002072/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2073 * the call-stack unwinds again.
2074 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002075void
Fred Drake100814d2000-07-09 15:48:49 +00002076_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002077{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002078 while (_PyRuntime.gc.trash_delete_later) {
2079 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002081
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002082 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002083 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 /* Call the deallocator directly. This used to try to
2086 * fool Py_DECREF into calling it indirectly, but
2087 * Py_DECREF was already called on this object, and in
2088 * assorted non-release builds calling Py_DECREF again ends
2089 * up distorting allocation statistics.
2090 */
Victor Stinner24702042018-10-26 17:16:37 +02002091 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002092 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002094 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002096}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002097
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002098/* The equivalent API, using per-thread state recursion info */
2099void
2100_PyTrash_thread_destroy_chain(void)
2101{
Victor Stinner50b48572018-11-01 01:51:40 +01002102 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002103 /* We need to increase trash_delete_nesting here, otherwise,
2104 _PyTrash_thread_destroy_chain will be called recursively
2105 and then possibly crash. An example that may crash without
2106 increase:
2107 N = 500000 # need to be large enough
2108 ob = object()
2109 tups = [(ob,) for i in range(N)]
2110 for i in range(49):
2111 tups = [(tup,) for tup in tups]
2112 del tups
2113 */
2114 assert(tstate->trash_delete_nesting == 0);
2115 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002116 while (tstate->trash_delete_later) {
2117 PyObject *op = tstate->trash_delete_later;
2118 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2119
2120 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002121 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002122
2123 /* Call the deallocator directly. This used to try to
2124 * fool Py_DECREF into calling it indirectly, but
2125 * Py_DECREF was already called on this object, and in
2126 * assorted non-release builds calling Py_DECREF again ends
2127 * up distorting allocation statistics.
2128 */
Victor Stinner24702042018-10-26 17:16:37 +02002129 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002130 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002131 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002132 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002133 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002134}
2135
Victor Stinner626bff82018-10-25 17:31:10 +02002136
2137void
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002138_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002139 const char *file, int line, const char *function)
2140{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002141 fprintf(stderr, "%s:%d: ", file, line);
2142 if (function) {
2143 fprintf(stderr, "%s: ", function);
2144 }
Victor Stinner626bff82018-10-25 17:31:10 +02002145 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002146 if (expr) {
2147 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002148 }
2149 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002150 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002151 }
2152 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002153 if (msg) {
2154 fprintf(stderr, ": %s", msg);
2155 }
2156 fprintf(stderr, "\n");
2157 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002158
2159 if (obj == NULL) {
2160 fprintf(stderr, "<NULL object>\n");
2161 }
2162 else if (_PyObject_IsFreed(obj)) {
2163 /* It seems like the object memory has been freed:
2164 don't access it to prevent a segmentation fault. */
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002165 fprintf(stderr, "<object: freed>\n");
2166 }
2167 else if (Py_TYPE(obj) == NULL) {
2168 fprintf(stderr, "<object: ob_type=NULL>\n");
2169 }
2170 else if (_PyObject_IsFreed((PyObject *)Py_TYPE(obj))) {
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002171 fprintf(stderr, "<object: freed type %p>\n", (void *)Py_TYPE(obj));
Victor Stinner626bff82018-10-25 17:31:10 +02002172 }
2173 else {
penguindustin96466302019-05-06 14:57:17 -04002174 /* Display the traceback where the object has been allocated.
Victor Stinner626bff82018-10-25 17:31:10 +02002175 Do it before dumping repr(obj), since repr() is more likely
2176 to crash than dumping the traceback. */
2177 void *ptr;
2178 PyTypeObject *type = Py_TYPE(obj);
2179 if (PyType_IS_GC(type)) {
2180 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2181 }
2182 else {
2183 ptr = (void *)obj;
2184 }
2185 _PyMem_DumpTraceback(fileno(stderr), ptr);
2186
2187 /* This might succeed or fail, but we're about to abort, so at least
2188 try to provide any extra info we can: */
2189 _PyObject_Dump(obj);
2190 }
2191 fflush(stderr);
2192
2193 Py_FatalError("_PyObject_AssertFailed");
2194}
2195
Victor Stinner3c09dca2018-10-30 14:48:26 +01002196
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002197#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002198
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002199void
2200_Py_Dealloc(PyObject *op)
2201{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002202 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2203#ifdef Py_TRACE_REFS
2204 _Py_ForgetReference(op);
2205#else
2206 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002207#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002208 (*dealloc)(op);
2209}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002210
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002211#ifdef __cplusplus
2212}
2213#endif