blob: cb727943cb342efe5178a13a0c27569aa310dcba [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 Stinner0fc91ee2019-04-12 21:51:34 +02005#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01006#include "pycore_pystate.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01007#include "pycore_context.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00008#include "frameobject.h"
Eric Snowc11183c2019-03-15 16:35:46 -06009#include "interpreteridobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011#ifdef __cplusplus
12extern "C" {
13#endif
14
Victor Stinner626bff82018-10-25 17:31:10 +020015/* Defined in tracemalloc.c */
16extern void _PyMem_DumpTraceback(int fd, const void *ptr);
17
Victor Stinnerbd303c12013-11-07 23:07:29 +010018_Py_IDENTIFIER(Py_Repr);
19_Py_IDENTIFIER(__bytes__);
20_Py_IDENTIFIER(__dir__);
21_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010022
Victor Stinner0fc91ee2019-04-12 21:51:34 +020023
24int
25_PyObject_CheckConsistency(PyObject *op, int check_content)
26{
27 _PyObject_ASSERT(op, op != NULL);
28 _PyObject_ASSERT(op, !_PyObject_IsFreed(op));
29 _PyObject_ASSERT(op, Py_REFCNT(op) >= 1);
30
31 PyTypeObject *type = op->ob_type;
32 _PyObject_ASSERT(op, type != NULL);
33 _PyType_CheckConsistency(type);
34
35 if (PyUnicode_Check(op)) {
36 _PyUnicode_CheckConsistency(op, check_content);
37 }
38 else if (PyDict_Check(op)) {
39 _PyDict_CheckConsistency(op, check_content);
40 }
41 return 1;
42}
43
44
Tim Peters34592512002-07-11 06:23:50 +000045#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000046Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000047
48Py_ssize_t
49_Py_GetRefTotal(void)
50{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 PyObject *o;
52 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020053 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 if (o != NULL)
55 total -= o->ob_refcnt;
56 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057}
Nick Coghland6009512014-11-20 21:39:37 +100058
59void
60_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070061 fprintf(stderr,
62 "[%" PY_FORMAT_SIZE_T "d refs, "
63 "%" PY_FORMAT_SIZE_T "d blocks]\n",
64 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100065}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000066#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067
Guido van Rossum3f5da241990-12-20 15:06:42 +000068/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
69 These are used by the individual routines for object creation.
70 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071
Tim Peters78be7992003-03-23 02:51:01 +000072#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000073/* Head of circular doubly-linked list of all objects. These are linked
74 * together via the _ob_prev and _ob_next members of a PyObject, which
75 * exist only in a Py_TRACE_REFS build.
76 */
Tim Peters78be7992003-03-23 02:51:01 +000077static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000078
Tim Peters7571a0f2003-03-23 17:52:28 +000079/* Insert op at the front of the list of all objects. If force is true,
80 * op is added even if _ob_prev and _ob_next are non-NULL already. If
81 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
82 * force should be true if and only if op points to freshly allocated,
83 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000084 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000085 * Note that objects are normally added to the list via _Py_NewReference,
86 * which is called by PyObject_Init. Not all objects are initialized that
87 * way, though; exceptions include statically allocated type objects, and
88 * statically allocated singletons (like Py_True and Py_None).
89 */
Tim Peters36eb4df2003-03-23 03:33:13 +000090void
Tim Peters7571a0f2003-03-23 17:52:28 +000091_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000092{
Tim Peters7571a0f2003-03-23 17:52:28 +000093#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 if (!force) {
95 /* If it's initialized memory, op must be in or out of
96 * the list unambiguously.
97 */
Victor Stinner24702042018-10-26 17:16:37 +020098 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 }
Tim Peters78be7992003-03-23 02:51:01 +0000100#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 if (force || op->_ob_prev == NULL) {
102 op->_ob_next = refchain._ob_next;
103 op->_ob_prev = &refchain;
104 refchain._ob_next->_ob_prev = op;
105 refchain._ob_next = op;
106 }
Tim Peters7571a0f2003-03-23 17:52:28 +0000107}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +0000109
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000110#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000112/* All types are added to type_list, at least when
113 they get one object created. That makes them
114 immortal, which unfortunately contributes to
115 garbage itself. If unlist_types_without_objects
116 is set, they will be removed from the type_list
117 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +0000118static int unlist_types_without_objects;
Pablo Galindo49c75a82018-10-28 15:02:17 +0000119extern Py_ssize_t _Py_tuple_zero_allocs, _Py_fast_tuple_allocs;
120extern Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
121extern Py_ssize_t _Py_null_strings, _Py_one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000122void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000123_Py_dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000124{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200125 PyInterpreterState *interp = _PyInterpreterState_Get();
Eddie Elizondo745dc652018-02-21 20:55:18 -0800126 if (!interp->core_config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300127 return;
Victor Stinner25420fe2017-11-20 18:12:22 -0800128 }
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000129
Eddie Elizondo745dc652018-02-21 20:55:18 -0800130 PyTypeObject *tp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 for (tp = type_list; tp; tp = tp->tp_next)
132 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
133 "freed: %" PY_FORMAT_SIZE_T "d, "
134 "max in use: %" PY_FORMAT_SIZE_T "d\n",
135 tp->tp_name, tp->tp_allocs, tp->tp_frees,
136 tp->tp_maxalloc);
137 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
138 "empty: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000139 _Py_fast_tuple_allocs, _Py_tuple_zero_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
141 "neg: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000142 _Py_quick_int_allocs, _Py_quick_neg_int_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
144 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000145 _Py_null_strings, _Py_one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000146}
147
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000148PyObject *
Pablo Galindo49c75a82018-10-28 15:02:17 +0000149_Py_get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyTypeObject *tp;
152 PyObject *result;
153 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 result = PyList_New(0);
156 if (result == NULL)
157 return NULL;
158 for (tp = type_list; tp; tp = tp->tp_next) {
159 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
160 tp->tp_frees, tp->tp_maxalloc);
161 if (v == NULL) {
162 Py_DECREF(result);
163 return NULL;
164 }
165 if (PyList_Append(result, v) < 0) {
166 Py_DECREF(v);
167 Py_DECREF(result);
168 return NULL;
169 }
170 Py_DECREF(v);
171 }
172 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000173}
174
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000175void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000176_Py_inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
179 /* first time; insert in linked list */
180 if (tp->tp_next != NULL) /* sanity check */
Pablo Galindo49c75a82018-10-28 15:02:17 +0000181 Py_FatalError("XXX _Py_inc_count sanity check");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (type_list)
183 type_list->tp_prev = tp;
184 tp->tp_next = type_list;
185 /* Note that as of Python 2.2, heap-allocated type objects
186 * can go away, but this code requires that they stay alive
187 * until program exit. That's why we're careful with
188 * refcounts here. type_list gets a new reference to tp,
189 * while ownership of the reference type_list used to hold
190 * (if any) was transferred to tp->tp_next in the line above.
191 * tp is thus effectively immortal after this.
192 */
193 Py_INCREF(tp);
194 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000195#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Also insert in the doubly-linked list of all objects,
197 * if not already there.
198 */
199 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000200#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 }
202 tp->tp_allocs++;
203 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
204 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000205}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206
Pablo Galindo49c75a82018-10-28 15:02:17 +0000207void _Py_dec_count(PyTypeObject *tp)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 tp->tp_frees++;
210 if (unlist_types_without_objects &&
211 tp->tp_allocs == tp->tp_frees) {
212 /* unlink the type from type_list */
213 if (tp->tp_prev)
214 tp->tp_prev->tp_next = tp->tp_next;
215 else
216 type_list = tp->tp_next;
217 if (tp->tp_next)
218 tp->tp_next->tp_prev = tp->tp_prev;
219 tp->tp_next = tp->tp_prev = NULL;
220 Py_DECREF(tp);
221 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000222}
223
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000224#endif
225
Tim Peters7c321a82002-07-09 02:57:01 +0000226#ifdef Py_REF_DEBUG
227/* Log a fatal error; doesn't return. */
228void
Victor Stinner18618e652018-10-25 17:28:11 +0200229_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000230{
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100231 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200232 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000233}
234
235#endif /* Py_REF_DEBUG */
236
Thomas Heller1328b522004-04-22 17:23:49 +0000237void
238Py_IncRef(PyObject *o)
239{
240 Py_XINCREF(o);
241}
242
243void
244Py_DecRef(PyObject *o)
245{
246 Py_XDECREF(o);
247}
248
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000249PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000250PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if (op == NULL)
253 return PyErr_NoMemory();
254 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
255 Py_TYPE(op) = tp;
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400256 if (PyType_GetFlags(tp) & Py_TPFLAGS_HEAPTYPE) {
257 Py_INCREF(tp);
258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 _Py_NewReference(op);
260 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261}
262
Guido van Rossumb18618d2000-05-03 23:44:39 +0000263PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000264PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (op == NULL)
267 return (PyVarObject *) PyErr_NoMemory();
268 /* Any changes should be reflected in PyObject_INIT_VAR */
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400269 Py_SIZE(op) = size;
270 PyObject_Init((PyObject *)op, tp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000272}
273
274PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000275_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 PyObject *op;
278 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
279 if (op == NULL)
280 return PyErr_NoMemory();
281 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000282}
283
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000284PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000285_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 PyVarObject *op;
288 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
289 op = (PyVarObject *) PyObject_MALLOC(size);
290 if (op == NULL)
291 return (PyVarObject *)PyErr_NoMemory();
292 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000293}
294
Antoine Pitrou796564c2013-07-30 19:59:21 +0200295void
296PyObject_CallFinalizer(PyObject *self)
297{
298 PyTypeObject *tp = Py_TYPE(self);
299
300 /* The former could happen on heaptypes created from the C API, e.g.
301 PyType_FromSpec(). */
302 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
303 tp->tp_finalize == NULL)
304 return;
305 /* tp_finalize should only be called once. */
306 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
307 return;
308
309 tp->tp_finalize(self);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900310 if (PyType_IS_GC(tp)) {
311 _PyGC_SET_FINALIZED(self);
312 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200313}
314
315int
316PyObject_CallFinalizerFromDealloc(PyObject *self)
317{
318 Py_ssize_t refcnt;
319
320 /* Temporarily resurrect the object. */
321 if (self->ob_refcnt != 0) {
322 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
323 "object with a non-zero refcount");
324 }
325 self->ob_refcnt = 1;
326
327 PyObject_CallFinalizer(self);
328
329 /* Undo the temporary resurrection; can't use DECREF here, it would
330 * cause a recursive call.
331 */
Victor Stinner24702042018-10-26 17:16:37 +0200332 _PyObject_ASSERT_WITH_MSG(self,
333 self->ob_refcnt > 0,
334 "refcount is too small");
Antoine Pitrou796564c2013-07-30 19:59:21 +0200335 if (--self->ob_refcnt == 0)
336 return 0; /* this is the normal path out */
337
338 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
339 * never happened.
340 */
341 refcnt = self->ob_refcnt;
342 _Py_NewReference(self);
343 self->ob_refcnt = refcnt;
344
Victor Stinner24702042018-10-26 17:16:37 +0200345 _PyObject_ASSERT(self,
346 (!PyType_IS_GC(Py_TYPE(self))
347 || _PyObject_GC_IS_TRACKED(self)));
Antoine Pitrou796564c2013-07-30 19:59:21 +0200348 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
349 * we need to undo that. */
350 _Py_DEC_REFTOTAL;
351 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
352 * chain, so no more to do there.
353 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
354 * _Py_NewReference bumped tp_allocs: both of those need to be
355 * undone.
356 */
357#ifdef COUNT_ALLOCS
358 --Py_TYPE(self)->tp_frees;
359 --Py_TYPE(self)->tp_allocs;
360#endif
361 return -1;
362}
363
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000364int
365PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (PyErr_CheckSignals())
369 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000370#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (PyOS_CheckStack()) {
372 PyErr_SetString(PyExc_MemoryError, "stack overflow");
373 return -1;
374 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000375#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 clearerr(fp); /* Clear any previous error condition */
377 if (op == NULL) {
378 Py_BEGIN_ALLOW_THREADS
379 fprintf(fp, "<nil>");
380 Py_END_ALLOW_THREADS
381 }
382 else {
Victor Stinner3ec9af72018-10-26 02:12:34 +0200383 if (op->ob_refcnt <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 /* XXX(twouters) cast refcount to long until %zd is
385 universally available */
386 Py_BEGIN_ALLOW_THREADS
387 fprintf(fp, "<refcnt %ld at %p>",
Zackery Spytz1a2252e2019-05-06 10:56:51 -0600388 (long)op->ob_refcnt, (void *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200390 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 else {
392 PyObject *s;
393 if (flags & Py_PRINT_RAW)
394 s = PyObject_Str(op);
395 else
396 s = PyObject_Repr(op);
397 if (s == NULL)
398 ret = -1;
399 else if (PyBytes_Check(s)) {
400 fwrite(PyBytes_AS_STRING(s), 1,
401 PyBytes_GET_SIZE(s), fp);
402 }
403 else if (PyUnicode_Check(s)) {
404 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200405 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600406 if (t == NULL) {
407 ret = -1;
408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 else {
410 fwrite(PyBytes_AS_STRING(t), 1,
411 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000412 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 }
414 }
415 else {
416 PyErr_Format(PyExc_TypeError,
417 "str() or repr() returned '%.100s'",
418 s->ob_type->tp_name);
419 ret = -1;
420 }
421 Py_XDECREF(s);
422 }
423 }
424 if (ret == 0) {
425 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300426 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 clearerr(fp);
428 ret = -1;
429 }
430 }
431 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000432}
433
Guido van Rossum38938152006-08-21 23:36:26 +0000434/* For debugging convenience. Set a breakpoint here and call it from your DLL */
435void
Thomas Woutersb2137042007-02-01 18:02:27 +0000436_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000437{
438}
439
Neal Norwitz1a997502003-01-13 20:13:12 +0000440
Victor Stinner4c409be2019-04-11 13:01:15 +0200441/* Heuristic checking if the object memory is uninitialized or deallocated.
442 Rely on the debug hooks on Python memory allocators:
443 see _PyMem_IsPtrFreed().
Victor Stinner82af0b62018-10-23 17:39:40 +0200444
445 The function can be used to prevent segmentation fault on dereferencing
Victor Stinner4c409be2019-04-11 13:01:15 +0200446 pointers like 0xDDDDDDDDDDDDDDDD. */
Victor Stinner82af0b62018-10-23 17:39:40 +0200447int
448_PyObject_IsFreed(PyObject *op)
449{
Victor Stinner2b00db62019-04-11 11:33:27 +0200450 if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(op->ob_type)) {
Victor Stinner2cf5d322018-11-22 16:32:57 +0100451 return 1;
452 }
Victor Stinner2b00db62019-04-11 11:33:27 +0200453 /* ignore op->ob_ref: its value can have be modified
Victor Stinner82af0b62018-10-23 17:39:40 +0200454 by Py_INCREF() and Py_DECREF(). */
455#ifdef Py_TRACE_REFS
Victor Stinner2b00db62019-04-11 11:33:27 +0200456 if (_PyMem_IsPtrFreed(op->_ob_next) || _PyMem_IsPtrFreed(op->_ob_prev)) {
457 return 1;
458 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200459#endif
Victor Stinner2b00db62019-04-11 11:33:27 +0200460 return 0;
Victor Stinner82af0b62018-10-23 17:39:40 +0200461}
462
463
Barry Warsaw9bf16442001-01-23 16:24:35 +0000464/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000465void
466_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000467{
Victor Stinner82af0b62018-10-23 17:39:40 +0200468 if (op == NULL) {
469 fprintf(stderr, "<NULL object>\n");
470 fflush(stderr);
471 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200473
474 if (_PyObject_IsFreed(op)) {
475 /* It seems like the object memory has been freed:
476 don't access it to prevent a segmentation fault. */
Victor Stinner2b00db62019-04-11 11:33:27 +0200477 fprintf(stderr, "<Freed object>\n");
Victor Stinner2cf5d322018-11-22 16:32:57 +0100478 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200479 }
480
481 PyGILState_STATE gil;
482 PyObject *error_type, *error_value, *error_traceback;
483
484 fprintf(stderr, "object : ");
485 fflush(stderr);
486 gil = PyGILState_Ensure();
487
488 PyErr_Fetch(&error_type, &error_value, &error_traceback);
489 (void)PyObject_Print(op, stderr, 0);
490 fflush(stderr);
491 PyErr_Restore(error_type, error_value, error_traceback);
492
493 PyGILState_Release(gil);
494 /* XXX(twouters) cast refcount to long until %zd is
495 universally available */
496 fprintf(stderr, "\n"
497 "type : %s\n"
498 "refcount: %ld\n"
499 "address : %p\n",
500 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
501 (long)op->ob_refcnt,
Zackery Spytz1a2252e2019-05-06 10:56:51 -0600502 (void *)op);
Victor Stinner82af0b62018-10-23 17:39:40 +0200503 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000504}
Barry Warsaw903138f2001-01-23 16:33:18 +0000505
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000507PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 PyObject *res;
510 if (PyErr_CheckSignals())
511 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000512#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (PyOS_CheckStack()) {
514 PyErr_SetString(PyExc_MemoryError, "stack overflow");
515 return NULL;
516 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000517#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 if (v == NULL)
519 return PyUnicode_FromString("<NULL>");
520 if (Py_TYPE(v)->tp_repr == NULL)
521 return PyUnicode_FromFormat("<%s object at %p>",
522 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200523
524#ifdef Py_DEBUG
525 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100526 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000527 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200528 assert(!PyErr_Occurred());
529#endif
530
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200531 /* It is possible for a type to have a tp_repr representation that loops
532 infinitely. */
533 if (Py_EnterRecursiveCall(" while getting the repr of an object"))
534 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 res = (*v->ob_type->tp_repr)(v);
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200536 Py_LeaveRecursiveCall();
Victor Stinner0a54cf12011-12-01 03:22:44 +0100537 if (res == NULL)
538 return NULL;
539 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 PyErr_Format(PyExc_TypeError,
541 "__repr__ returned non-string (type %.200s)",
542 res->ob_type->tp_name);
543 Py_DECREF(res);
544 return NULL;
545 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100546#ifndef Py_DEBUG
547 if (PyUnicode_READY(res) < 0)
548 return NULL;
549#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000551}
552
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000554PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyObject *res;
557 if (PyErr_CheckSignals())
558 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000559#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (PyOS_CheckStack()) {
561 PyErr_SetString(PyExc_MemoryError, "stack overflow");
562 return NULL;
563 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000564#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (v == NULL)
566 return PyUnicode_FromString("<NULL>");
567 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100568#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100569 if (PyUnicode_READY(v) < 0)
570 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100571#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 Py_INCREF(v);
573 return v;
574 }
575 if (Py_TYPE(v)->tp_str == NULL)
576 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000577
Victor Stinner33824f62013-08-26 14:05:19 +0200578#ifdef Py_DEBUG
579 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100580 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000581 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200582 assert(!PyErr_Occurred());
583#endif
584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 /* It is possible for a type to have a tp_str representation that loops
586 infinitely. */
587 if (Py_EnterRecursiveCall(" while getting the str of an object"))
588 return NULL;
589 res = (*Py_TYPE(v)->tp_str)(v);
590 Py_LeaveRecursiveCall();
591 if (res == NULL)
592 return NULL;
593 if (!PyUnicode_Check(res)) {
594 PyErr_Format(PyExc_TypeError,
595 "__str__ returned non-string (type %.200s)",
596 Py_TYPE(res)->tp_name);
597 Py_DECREF(res);
598 return NULL;
599 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100600#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100601 if (PyUnicode_READY(res) < 0)
602 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100603#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100604 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000606}
607
Georg Brandl559e5d72008-06-11 18:37:52 +0000608PyObject *
609PyObject_ASCII(PyObject *v)
610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 repr = PyObject_Repr(v);
614 if (repr == NULL)
615 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000616
Victor Stinneraf037572013-04-14 18:44:10 +0200617 if (PyUnicode_IS_ASCII(repr))
618 return repr;
619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200621 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 Py_DECREF(repr);
623 if (ascii == NULL)
624 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 res = PyUnicode_DecodeASCII(
627 PyBytes_AS_STRING(ascii),
628 PyBytes_GET_SIZE(ascii),
629 NULL);
630
631 Py_DECREF(ascii);
632 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000633}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000634
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000635PyObject *
636PyObject_Bytes(PyObject *v)
637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (v == NULL)
641 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (PyBytes_CheckExact(v)) {
644 Py_INCREF(v);
645 return v;
646 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000647
Benjamin Petersonce798522012-01-22 11:24:29 -0500648 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100650 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 Py_DECREF(func);
652 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000653 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000655 PyErr_Format(PyExc_TypeError,
656 "__bytes__ returned non-bytes (type %.200s)",
657 Py_TYPE(result)->tp_name);
658 Py_DECREF(result);
659 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 }
661 return result;
662 }
663 else if (PyErr_Occurred())
664 return NULL;
665 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000666}
667
Mark Dickinsonc008a172009-02-01 13:59:22 +0000668/* For Python 3.0.1 and later, the old three-way comparison has been
669 completely removed in favour of rich comparisons. PyObject_Compare() and
670 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000671 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000672 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000673
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000674 See (*) below for practical amendments.
675
Mark Dickinsonc008a172009-02-01 13:59:22 +0000676 tp_richcompare gets called with a first argument of the appropriate type
677 and a second object of an arbitrary type. We never do any kind of
678 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000679
Mark Dickinsonc008a172009-02-01 13:59:22 +0000680 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000681
682 NULL if an exception occurred
683 NotImplemented if the requested comparison is not implemented
684 any other false value if the requested comparison is false
685 any other true value if the requested comparison is true
686
687 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
688 NotImplemented.
689
690 (*) Practical amendments:
691
692 - If rich comparison returns NotImplemented, == and != are decided by
693 comparing the object pointer (i.e. falling back to the base object
694 implementation).
695
Guido van Rossuma4073002002-05-31 20:03:54 +0000696*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000697
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000698/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000699int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000700
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200701static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000702
703/* Perform a rich comparison, raising TypeError when the requested comparison
704 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000705static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000706do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 richcmpfunc f;
709 PyObject *res;
710 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (v->ob_type != w->ob_type &&
713 PyType_IsSubtype(w->ob_type, v->ob_type) &&
714 (f = w->ob_type->tp_richcompare) != NULL) {
715 checked_reverse_op = 1;
716 res = (*f)(w, v, _Py_SwappedOp[op]);
717 if (res != Py_NotImplemented)
718 return res;
719 Py_DECREF(res);
720 }
721 if ((f = v->ob_type->tp_richcompare) != NULL) {
722 res = (*f)(v, w, op);
723 if (res != Py_NotImplemented)
724 return res;
725 Py_DECREF(res);
726 }
727 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
728 res = (*f)(w, v, _Py_SwappedOp[op]);
729 if (res != Py_NotImplemented)
730 return res;
731 Py_DECREF(res);
732 }
733 /* If neither object implements it, provide a sensible default
734 for == and !=, but raise an exception for ordering. */
735 switch (op) {
736 case Py_EQ:
737 res = (v == w) ? Py_True : Py_False;
738 break;
739 case Py_NE:
740 res = (v != w) ? Py_True : Py_False;
741 break;
742 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyErr_Format(PyExc_TypeError,
Victor Stinner91108f02015-10-14 18:25:31 +0200744 "'%s' not supported between instances of '%.100s' and '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 opstrings[op],
Victor Stinner91108f02015-10-14 18:25:31 +0200746 v->ob_type->tp_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 w->ob_type->tp_name);
748 return NULL;
749 }
750 Py_INCREF(res);
751 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000752}
753
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000754/* Perform a rich comparison with object result. This wraps do_richcompare()
755 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000756
Guido van Rossume797ec12001-01-17 15:24:28 +0000757PyObject *
758PyObject_RichCompare(PyObject *v, PyObject *w, int op)
759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 assert(Py_LT <= op && op <= Py_GE);
763 if (v == NULL || w == NULL) {
764 if (!PyErr_Occurred())
765 PyErr_BadInternalCall();
766 return NULL;
767 }
768 if (Py_EnterRecursiveCall(" in comparison"))
769 return NULL;
770 res = do_richcompare(v, w, op);
771 Py_LeaveRecursiveCall();
772 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000773}
774
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000775/* Perform a rich comparison with integer result. This wraps
776 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000777int
778PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyObject *res;
781 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* Quick result when objects are the same.
784 Guarantees that identity implies equality. */
785 if (v == w) {
786 if (op == Py_EQ)
787 return 1;
788 else if (op == Py_NE)
789 return 0;
790 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 res = PyObject_RichCompare(v, w, op);
793 if (res == NULL)
794 return -1;
795 if (PyBool_Check(res))
796 ok = (res == Py_True);
797 else
798 ok = PyObject_IsTrue(res);
799 Py_DECREF(res);
800 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000801}
Fred Drake13634cf2000-06-29 19:17:04 +0000802
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100803Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000804PyObject_HashNotImplemented(PyObject *v)
805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
807 Py_TYPE(v)->tp_name);
808 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000809}
Fred Drake13634cf2000-06-29 19:17:04 +0000810
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000811Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000812PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyTypeObject *tp = Py_TYPE(v);
815 if (tp->tp_hash != NULL)
816 return (*tp->tp_hash)(v);
817 /* To keep to the general practice that inheriting
818 * solely from object in C code should work without
819 * an explicit call to PyType_Ready, we implicitly call
820 * PyType_Ready here and then check the tp_hash slot again
821 */
822 if (tp->tp_dict == NULL) {
823 if (PyType_Ready(tp) < 0)
824 return -1;
825 if (tp->tp_hash != NULL)
826 return (*tp->tp_hash)(v);
827 }
828 /* Otherwise, the object can't be hashed */
829 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000830}
831
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000832PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000833PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (Py_TYPE(v)->tp_getattr != NULL)
838 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900839 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (w == NULL)
841 return NULL;
842 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100843 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000845}
846
847int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000848PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyObject *res = PyObject_GetAttrString(v, name);
851 if (res != NULL) {
852 Py_DECREF(res);
853 return 1;
854 }
855 PyErr_Clear();
856 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000857}
858
859int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000860PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyObject *s;
863 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (Py_TYPE(v)->tp_setattr != NULL)
866 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
867 s = PyUnicode_InternFromString(name);
868 if (s == NULL)
869 return -1;
870 res = PyObject_SetAttr(v, s, w);
871 Py_XDECREF(s);
872 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000873}
874
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500875int
876_PyObject_IsAbstract(PyObject *obj)
877{
878 int res;
879 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500880
881 if (obj == NULL)
882 return 0;
883
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200884 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
885 if (res > 0) {
886 res = PyObject_IsTrue(isabstract);
887 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500888 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500889 return res;
890}
891
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000892PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200893_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
894{
895 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100896 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200897 if (!oname)
898 return NULL;
899 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200900 return result;
901}
902
903int
904_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
905{
906 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100907 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200908 if (!oname)
909 return -1;
910 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200911 return result;
912}
913
914int
915_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
916{
917 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100918 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200919 if (!oname)
920 return -1;
921 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200922 return result;
923}
924
925PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000926PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 if (!PyUnicode_Check(name)) {
931 PyErr_Format(PyExc_TypeError,
932 "attribute name must be string, not '%.200s'",
933 name->ob_type->tp_name);
934 return NULL;
935 }
936 if (tp->tp_getattro != NULL)
937 return (*tp->tp_getattro)(v, name);
938 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200939 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (name_str == NULL)
941 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200942 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 }
944 PyErr_Format(PyExc_AttributeError,
945 "'%.50s' object has no attribute '%U'",
946 tp->tp_name, name);
947 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000948}
949
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200950int
951_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900952{
953 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900954
955 if (!PyUnicode_Check(name)) {
956 PyErr_Format(PyExc_TypeError,
957 "attribute name must be string, not '%.200s'",
958 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200959 *result = NULL;
960 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900961 }
962
963 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200964 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
965 if (*result != NULL) {
966 return 1;
967 }
968 if (PyErr_Occurred()) {
969 return -1;
970 }
971 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900972 }
973 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200974 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900975 }
976 else if (tp->tp_getattr != NULL) {
977 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200978 if (name_str == NULL) {
979 *result = NULL;
980 return -1;
981 }
982 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900983 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900984 else {
985 *result = NULL;
986 return 0;
987 }
988
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200989 if (*result != NULL) {
990 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900991 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200992 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
993 return -1;
994 }
995 PyErr_Clear();
996 return 0;
997}
998
999int
1000_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
1001{
1002 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
1003 if (!oname) {
1004 *result = NULL;
1005 return -1;
1006 }
1007 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +09001008}
1009
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001010int
Fred Drake100814d2000-07-09 15:48:49 +00001011PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001012{
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001013 PyObject *res;
1014 if (_PyObject_LookupAttr(v, name, &res) < 0) {
1015 PyErr_Clear();
1016 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001018 if (res == NULL) {
1019 return 0;
1020 }
1021 Py_DECREF(res);
1022 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001023}
1024
1025int
Fred Drake100814d2000-07-09 15:48:49 +00001026PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyTypeObject *tp = Py_TYPE(v);
1029 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (!PyUnicode_Check(name)) {
1032 PyErr_Format(PyExc_TypeError,
1033 "attribute name must be string, not '%.200s'",
1034 name->ob_type->tp_name);
1035 return -1;
1036 }
1037 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 PyUnicode_InternInPlace(&name);
1040 if (tp->tp_setattro != NULL) {
1041 err = (*tp->tp_setattro)(v, name, value);
1042 Py_DECREF(name);
1043 return err;
1044 }
1045 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001046 const char *name_str = PyUnicode_AsUTF8(name);
Zackery Spytze0dcb852019-04-28 06:58:52 -06001047 if (name_str == NULL) {
1048 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 return -1;
Zackery Spytze0dcb852019-04-28 06:58:52 -06001050 }
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001051 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 Py_DECREF(name);
1053 return err;
1054 }
1055 Py_DECREF(name);
Victor Stinner24702042018-10-26 17:16:37 +02001056 _PyObject_ASSERT(name, name->ob_refcnt >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1058 PyErr_Format(PyExc_TypeError,
1059 "'%.100s' object has no attributes "
1060 "(%s .%U)",
1061 tp->tp_name,
1062 value==NULL ? "del" : "assign to",
1063 name);
1064 else
1065 PyErr_Format(PyExc_TypeError,
1066 "'%.100s' object has only read-only attributes "
1067 "(%s .%U)",
1068 tp->tp_name,
1069 value==NULL ? "del" : "assign to",
1070 name);
1071 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072}
1073
1074/* Helper to get a pointer to an object's __dict__ slot, if any */
1075
1076PyObject **
1077_PyObject_GetDictPtr(PyObject *obj)
1078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 Py_ssize_t dictoffset;
1080 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 dictoffset = tp->tp_dictoffset;
1083 if (dictoffset == 0)
1084 return NULL;
1085 if (dictoffset < 0) {
1086 Py_ssize_t tsize;
1087 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 tsize = ((PyVarObject *)obj)->ob_size;
1090 if (tsize < 0)
1091 tsize = -tsize;
1092 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001095 _PyObject_ASSERT(obj, dictoffset > 0);
1096 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 }
1098 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099}
1100
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001102PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 Py_INCREF(obj);
1105 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001106}
1107
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001108/* Helper used when the __next__ method is removed from a type:
1109 tp_iternext is never NULL and can be safely called without checking
1110 on every iteration.
1111 */
1112
1113PyObject *
1114_PyObject_NextNotImplemented(PyObject *self)
1115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 PyErr_Format(PyExc_TypeError,
1117 "'%.200s' object is not iterable",
1118 Py_TYPE(self)->tp_name);
1119 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001120}
1121
Yury Selivanovf2392132016-12-13 19:03:51 -05001122
1123/* Specialized version of _PyObject_GenericGetAttrWithDict
1124 specifically for the LOAD_METHOD opcode.
1125
1126 Return 1 if a method is found, 0 if it's a regular attribute
1127 from __dict__ or something returned by using a descriptor
1128 protocol.
1129
1130 `method` will point to the resolved attribute or NULL. In the
1131 latter case, an error will be set.
1132*/
1133int
1134_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1135{
1136 PyTypeObject *tp = Py_TYPE(obj);
1137 PyObject *descr;
1138 descrgetfunc f = NULL;
1139 PyObject **dictptr, *dict;
1140 PyObject *attr;
1141 int meth_found = 0;
1142
1143 assert(*method == NULL);
1144
1145 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1146 || !PyUnicode_Check(name)) {
1147 *method = PyObject_GetAttr(obj, name);
1148 return 0;
1149 }
1150
1151 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1152 return 0;
1153
1154 descr = _PyType_Lookup(tp, name);
1155 if (descr != NULL) {
1156 Py_INCREF(descr);
INADA Naoki5566bbb2017-02-03 07:43:03 +09001157 if (PyFunction_Check(descr) ||
1158 (Py_TYPE(descr) == &PyMethodDescr_Type)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001159 meth_found = 1;
1160 } else {
1161 f = descr->ob_type->tp_descr_get;
1162 if (f != NULL && PyDescr_IsData(descr)) {
1163 *method = f(descr, obj, (PyObject *)obj->ob_type);
1164 Py_DECREF(descr);
1165 return 0;
1166 }
1167 }
1168 }
1169
1170 dictptr = _PyObject_GetDictPtr(obj);
1171 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1172 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001173 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001174 if (attr != NULL) {
1175 Py_INCREF(attr);
1176 *method = attr;
1177 Py_DECREF(dict);
1178 Py_XDECREF(descr);
1179 return 0;
1180 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001181 else {
1182 Py_DECREF(dict);
1183 if (PyErr_Occurred()) {
1184 Py_XDECREF(descr);
1185 return 0;
1186 }
1187 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001188 }
1189
1190 if (meth_found) {
1191 *method = descr;
1192 return 1;
1193 }
1194
1195 if (f != NULL) {
1196 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1197 Py_DECREF(descr);
1198 return 0;
1199 }
1200
1201 if (descr != NULL) {
1202 *method = descr;
1203 return 0;
1204 }
1205
1206 PyErr_Format(PyExc_AttributeError,
1207 "'%.50s' object has no attribute '%U'",
1208 tp->tp_name, name);
1209 return 0;
1210}
1211
1212/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001213
Raymond Hettinger01538262003-03-17 08:24:35 +00001214PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001215_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1216 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217{
Yury Selivanovf2392132016-12-13 19:03:51 -05001218 /* Make sure the logic of _PyObject_GetMethod is in sync with
1219 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001220
1221 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001222 */
1223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyTypeObject *tp = Py_TYPE(obj);
1225 PyObject *descr = NULL;
1226 PyObject *res = NULL;
1227 descrgetfunc f;
1228 Py_ssize_t dictoffset;
1229 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (!PyUnicode_Check(name)){
1232 PyErr_Format(PyExc_TypeError,
1233 "attribute name must be string, not '%.200s'",
1234 name->ob_type->tp_name);
1235 return NULL;
1236 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001237 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 if (tp->tp_dict == NULL) {
1240 if (PyType_Ready(tp) < 0)
1241 goto done;
1242 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 f = NULL;
1247 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001248 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 f = descr->ob_type->tp_descr_get;
1250 if (f != NULL && PyDescr_IsData(descr)) {
1251 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001252 if (res == NULL && suppress &&
1253 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1254 PyErr_Clear();
1255 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 goto done;
1257 }
1258 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001259
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001260 if (dict == NULL) {
1261 /* Inline _PyObject_GetDictPtr */
1262 dictoffset = tp->tp_dictoffset;
1263 if (dictoffset != 0) {
1264 if (dictoffset < 0) {
1265 Py_ssize_t tsize;
1266 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001267
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001268 tsize = ((PyVarObject *)obj)->ob_size;
1269 if (tsize < 0)
1270 tsize = -tsize;
1271 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001272 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001273
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001274 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001275 _PyObject_ASSERT(obj, dictoffset > 0);
1276 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001278 dictptr = (PyObject **) ((char *)obj + dictoffset);
1279 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 }
1281 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001282 if (dict != NULL) {
1283 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001284 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001285 if (res != NULL) {
1286 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001287 Py_DECREF(dict);
1288 goto done;
1289 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001290 else {
1291 Py_DECREF(dict);
1292 if (PyErr_Occurred()) {
1293 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1294 PyErr_Clear();
1295 }
1296 else {
1297 goto done;
1298 }
1299 }
1300 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001301 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (f != NULL) {
1304 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001305 if (res == NULL && suppress &&
1306 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1307 PyErr_Clear();
1308 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 goto done;
1310 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (descr != NULL) {
1313 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001314 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 goto done;
1316 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001317
INADA Naoki378edee2018-01-16 20:52:41 +09001318 if (!suppress) {
1319 PyErr_Format(PyExc_AttributeError,
1320 "'%.50s' object has no attribute '%U'",
1321 tp->tp_name, name);
1322 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001323 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001324 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 Py_DECREF(name);
1326 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327}
1328
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001329PyObject *
1330PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1331{
INADA Naoki378edee2018-01-16 20:52:41 +09001332 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001333}
1334
Tim Peters6d6c1a32001-08-02 04:15:00 +00001335int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001336_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1337 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 PyTypeObject *tp = Py_TYPE(obj);
1340 PyObject *descr;
1341 descrsetfunc f;
1342 PyObject **dictptr;
1343 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (!PyUnicode_Check(name)){
1346 PyErr_Format(PyExc_TypeError,
1347 "attribute name must be string, not '%.200s'",
1348 name->ob_type->tp_name);
1349 return -1;
1350 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001351
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001352 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1353 return -1;
1354
1355 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001360 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001362 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 res = f(descr, obj, value);
1364 goto done;
1365 }
1366 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001368 if (dict == NULL) {
1369 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001370 if (dictptr == NULL) {
1371 if (descr == NULL) {
1372 PyErr_Format(PyExc_AttributeError,
1373 "'%.100s' object has no attribute '%U'",
1374 tp->tp_name, name);
1375 }
1376 else {
1377 PyErr_Format(PyExc_AttributeError,
1378 "'%.50s' object attribute '%U' is read-only",
1379 tp->tp_name, name);
1380 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001381 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001383 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001384 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001385 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001386 Py_INCREF(dict);
1387 if (value == NULL)
1388 res = PyDict_DelItem(dict, name);
1389 else
1390 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001391 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001393 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1394 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001395
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001396 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001397 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 Py_DECREF(name);
1399 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001400}
1401
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001402int
1403PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1404{
1405 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1406}
1407
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001408int
1409PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1410{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001411 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001412 if (dictptr == NULL) {
1413 PyErr_SetString(PyExc_AttributeError,
1414 "This object has no __dict__");
1415 return -1;
1416 }
1417 if (value == NULL) {
1418 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1419 return -1;
1420 }
1421 if (!PyDict_Check(value)) {
1422 PyErr_Format(PyExc_TypeError,
1423 "__dict__ must be set to a dictionary, "
1424 "not a '%.200s'", Py_TYPE(value)->tp_name);
1425 return -1;
1426 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001427 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001428 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001429 return 0;
1430}
1431
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001432
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001433/* Test a value used as condition, e.g., in a for or if statement.
1434 Return -1 if an error occurred */
1435
1436int
Fred Drake100814d2000-07-09 15:48:49 +00001437PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 Py_ssize_t res;
1440 if (v == Py_True)
1441 return 1;
1442 if (v == Py_False)
1443 return 0;
1444 if (v == Py_None)
1445 return 0;
1446 else if (v->ob_type->tp_as_number != NULL &&
1447 v->ob_type->tp_as_number->nb_bool != NULL)
1448 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1449 else if (v->ob_type->tp_as_mapping != NULL &&
1450 v->ob_type->tp_as_mapping->mp_length != NULL)
1451 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1452 else if (v->ob_type->tp_as_sequence != NULL &&
1453 v->ob_type->tp_as_sequence->sq_length != NULL)
1454 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1455 else
1456 return 1;
1457 /* if it is negative, it should be either -1 or -2 */
1458 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001459}
1460
Tim Peters803526b2002-07-07 05:13:56 +00001461/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001462 Return -1 if an error occurred */
1463
1464int
Fred Drake100814d2000-07-09 15:48:49 +00001465PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 int res;
1468 res = PyObject_IsTrue(v);
1469 if (res < 0)
1470 return res;
1471 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001472}
1473
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001474/* Test whether an object can be called */
1475
1476int
Fred Drake100814d2000-07-09 15:48:49 +00001477PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (x == NULL)
1480 return 0;
1481 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001482}
1483
Tim Peters7eea37e2001-09-04 22:08:56 +00001484
Georg Brandle32b4222007-03-10 22:13:27 +00001485/* Helper for PyObject_Dir without arguments: returns the local scope. */
1486static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001487_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001490 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001491
Victor Stinner41bb43a2013-10-29 01:19:37 +01001492 locals = PyEval_GetLocals();
1493 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 names = PyMapping_Keys(locals);
1497 if (!names)
1498 return NULL;
1499 if (!PyList_Check(names)) {
1500 PyErr_Format(PyExc_TypeError,
1501 "dir(): expected keys() of locals to be a list, "
1502 "not '%.200s'", Py_TYPE(names)->tp_name);
1503 Py_DECREF(names);
1504 return NULL;
1505 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001506 if (PyList_Sort(names)) {
1507 Py_DECREF(names);
1508 return NULL;
1509 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 /* the locals don't need to be DECREF'd */
1511 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001512}
1513
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001514/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001515static PyObject *
1516_dir_object(PyObject *obj)
1517{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001518 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001519 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001520
Victor Stinner24702042018-10-26 17:16:37 +02001521 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001523 if (!PyErr_Occurred())
1524 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1525 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001527 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001528 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001529 Py_DECREF(dirfunc);
1530 if (result == NULL)
1531 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001532 /* return sorted(result) */
1533 sorted = PySequence_List(result);
1534 Py_DECREF(result);
1535 if (sorted == NULL)
1536 return NULL;
1537 if (PyList_Sort(sorted)) {
1538 Py_DECREF(sorted);
1539 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001541 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001542}
1543
1544/* Implementation of dir() -- if obj is NULL, returns the names in the current
1545 (local) scope. Otherwise, performs introspection of the object: returns a
1546 sorted list of attribute names (supposedly) accessible from the object
1547*/
1548PyObject *
1549PyObject_Dir(PyObject *obj)
1550{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001551 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001552}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001553
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001554/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001555None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001556There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001557so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001558*/
1559
Guido van Rossum0c182a11992-03-27 17:26:13 +00001560/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001561static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001562none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001565}
1566
Barry Warsaw9bf16442001-01-23 16:24:35 +00001567/* ARGUSED */
1568static void
Tim Peters803526b2002-07-07 05:13:56 +00001569none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* This should never get called, but we also don't want to SEGV if
1572 * we accidentally decref None out of existence.
1573 */
1574 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001575}
1576
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001577static PyObject *
1578none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1579{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001580 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001581 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1582 return NULL;
1583 }
1584 Py_RETURN_NONE;
1585}
1586
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001587static int
1588none_bool(PyObject *v)
1589{
1590 return 0;
1591}
1592
1593static PyNumberMethods none_as_number = {
1594 0, /* nb_add */
1595 0, /* nb_subtract */
1596 0, /* nb_multiply */
1597 0, /* nb_remainder */
1598 0, /* nb_divmod */
1599 0, /* nb_power */
1600 0, /* nb_negative */
1601 0, /* nb_positive */
1602 0, /* nb_absolute */
1603 (inquiry)none_bool, /* nb_bool */
1604 0, /* nb_invert */
1605 0, /* nb_lshift */
1606 0, /* nb_rshift */
1607 0, /* nb_and */
1608 0, /* nb_xor */
1609 0, /* nb_or */
1610 0, /* nb_int */
1611 0, /* nb_reserved */
1612 0, /* nb_float */
1613 0, /* nb_inplace_add */
1614 0, /* nb_inplace_subtract */
1615 0, /* nb_inplace_multiply */
1616 0, /* nb_inplace_remainder */
1617 0, /* nb_inplace_power */
1618 0, /* nb_inplace_lshift */
1619 0, /* nb_inplace_rshift */
1620 0, /* nb_inplace_and */
1621 0, /* nb_inplace_xor */
1622 0, /* nb_inplace_or */
1623 0, /* nb_floor_divide */
1624 0, /* nb_true_divide */
1625 0, /* nb_inplace_floor_divide */
1626 0, /* nb_inplace_true_divide */
1627 0, /* nb_index */
1628};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001629
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001630PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1632 "NoneType",
1633 0,
1634 0,
1635 none_dealloc, /*tp_dealloc*/ /*never called*/
1636 0, /*tp_print*/
1637 0, /*tp_getattr*/
1638 0, /*tp_setattr*/
1639 0, /*tp_reserved*/
1640 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001641 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 0, /*tp_as_sequence*/
1643 0, /*tp_as_mapping*/
1644 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001645 0, /*tp_call */
1646 0, /*tp_str */
1647 0, /*tp_getattro */
1648 0, /*tp_setattro */
1649 0, /*tp_as_buffer */
1650 Py_TPFLAGS_DEFAULT, /*tp_flags */
1651 0, /*tp_doc */
1652 0, /*tp_traverse */
1653 0, /*tp_clear */
1654 0, /*tp_richcompare */
1655 0, /*tp_weaklistoffset */
1656 0, /*tp_iter */
1657 0, /*tp_iternext */
1658 0, /*tp_methods */
1659 0, /*tp_members */
1660 0, /*tp_getset */
1661 0, /*tp_base */
1662 0, /*tp_dict */
1663 0, /*tp_descr_get */
1664 0, /*tp_descr_set */
1665 0, /*tp_dictoffset */
1666 0, /*tp_init */
1667 0, /*tp_alloc */
1668 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001669};
1670
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001671PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001672 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001673 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001674};
1675
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001676/* NotImplemented is an object that can be used to signal that an
1677 operation is not implemented for the given type combination. */
1678
1679static PyObject *
1680NotImplemented_repr(PyObject *op)
1681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001683}
1684
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001685static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301686NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001687{
1688 return PyUnicode_FromString("NotImplemented");
1689}
1690
1691static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301692 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001693 {NULL, NULL}
1694};
1695
1696static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001697notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1698{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001699 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001700 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1701 return NULL;
1702 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001703 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001704}
1705
Armin Ronacher226b1db2012-10-06 14:28:58 +02001706static void
1707notimplemented_dealloc(PyObject* ignore)
1708{
1709 /* This should never get called, but we also don't want to SEGV if
1710 * we accidentally decref NotImplemented out of existence.
1711 */
1712 Py_FatalError("deallocating NotImplemented");
1713}
1714
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001715PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1717 "NotImplementedType",
1718 0,
1719 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001720 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 0, /*tp_print*/
1722 0, /*tp_getattr*/
1723 0, /*tp_setattr*/
1724 0, /*tp_reserved*/
1725 NotImplemented_repr, /*tp_repr*/
1726 0, /*tp_as_number*/
1727 0, /*tp_as_sequence*/
1728 0, /*tp_as_mapping*/
1729 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001730 0, /*tp_call */
1731 0, /*tp_str */
1732 0, /*tp_getattro */
1733 0, /*tp_setattro */
1734 0, /*tp_as_buffer */
1735 Py_TPFLAGS_DEFAULT, /*tp_flags */
1736 0, /*tp_doc */
1737 0, /*tp_traverse */
1738 0, /*tp_clear */
1739 0, /*tp_richcompare */
1740 0, /*tp_weaklistoffset */
1741 0, /*tp_iter */
1742 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001743 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001744 0, /*tp_members */
1745 0, /*tp_getset */
1746 0, /*tp_base */
1747 0, /*tp_dict */
1748 0, /*tp_descr_get */
1749 0, /*tp_descr_set */
1750 0, /*tp_dictoffset */
1751 0, /*tp_init */
1752 0, /*tp_alloc */
1753 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001754};
1755
1756PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001758 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001759};
1760
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001761_PyInitError
Victor Stinnerab672812019-01-23 15:04:40 +01001762_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001763{
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001764#define INIT_TYPE(TYPE, NAME) \
1765 do { \
1766 if (PyType_Ready(TYPE) < 0) { \
1767 return _Py_INIT_ERR("Can't initialize " NAME " type"); \
1768 } \
1769 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001770
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001771 INIT_TYPE(&PyBaseObject_Type, "object");
1772 INIT_TYPE(&PyType_Type, "type");
1773 INIT_TYPE(&_PyWeakref_RefType, "weakref");
1774 INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
1775 INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
1776 INIT_TYPE(&PyLong_Type, "int");
1777 INIT_TYPE(&PyBool_Type, "bool");
1778 INIT_TYPE(&PyByteArray_Type, "bytearray");
1779 INIT_TYPE(&PyBytes_Type, "str");
1780 INIT_TYPE(&PyList_Type, "list");
1781 INIT_TYPE(&_PyNone_Type, "None");
1782 INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
1783 INIT_TYPE(&PyTraceBack_Type, "traceback");
1784 INIT_TYPE(&PySuper_Type, "super");
1785 INIT_TYPE(&PyRange_Type, "range");
1786 INIT_TYPE(&PyDict_Type, "dict");
1787 INIT_TYPE(&PyDictKeys_Type, "dict keys");
1788 INIT_TYPE(&PyDictValues_Type, "dict values");
1789 INIT_TYPE(&PyDictItems_Type, "dict items");
1790 INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
1791 INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
1792 INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
1793 INIT_TYPE(&PyODict_Type, "OrderedDict");
1794 INIT_TYPE(&PyODictKeys_Type, "odict_keys");
1795 INIT_TYPE(&PyODictItems_Type, "odict_items");
1796 INIT_TYPE(&PyODictValues_Type, "odict_values");
1797 INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
1798 INIT_TYPE(&PySet_Type, "set");
1799 INIT_TYPE(&PyUnicode_Type, "str");
1800 INIT_TYPE(&PySlice_Type, "slice");
1801 INIT_TYPE(&PyStaticMethod_Type, "static method");
1802 INIT_TYPE(&PyComplex_Type, "complex");
1803 INIT_TYPE(&PyFloat_Type, "float");
1804 INIT_TYPE(&PyFrozenSet_Type, "frozenset");
1805 INIT_TYPE(&PyProperty_Type, "property");
1806 INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
1807 INIT_TYPE(&PyMemoryView_Type, "memoryview");
1808 INIT_TYPE(&PyTuple_Type, "tuple");
1809 INIT_TYPE(&PyEnum_Type, "enumerate");
1810 INIT_TYPE(&PyReversed_Type, "reversed");
1811 INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
1812 INIT_TYPE(&PyCode_Type, "code");
1813 INIT_TYPE(&PyFrame_Type, "frame");
1814 INIT_TYPE(&PyCFunction_Type, "builtin function");
1815 INIT_TYPE(&PyMethod_Type, "method");
1816 INIT_TYPE(&PyFunction_Type, "function");
1817 INIT_TYPE(&PyDictProxy_Type, "dict proxy");
1818 INIT_TYPE(&PyGen_Type, "generator");
1819 INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
1820 INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
1821 INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
1822 INIT_TYPE(&PyEllipsis_Type, "ellipsis");
1823 INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
1824 INIT_TYPE(&_PyNamespace_Type, "namespace");
1825 INIT_TYPE(&PyCapsule_Type, "capsule");
1826 INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
1827 INIT_TYPE(&PyCell_Type, "cell");
1828 INIT_TYPE(&PyInstanceMethod_Type, "instance method");
1829 INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
1830 INIT_TYPE(&PyMethodDescr_Type, "method descr");
1831 INIT_TYPE(&PyCallIter_Type, "call iter");
1832 INIT_TYPE(&PySeqIter_Type, "sequence iterator");
1833 INIT_TYPE(&PyCoro_Type, "coroutine");
1834 INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
Eric Snowc11183c2019-03-15 16:35:46 -06001835 INIT_TYPE(&_PyInterpreterID_Type, "interpreter ID");
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001836 return _Py_INIT_OK();
Guido van Rossumba21a492001-08-16 08:17:26 +00001837
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001838#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001839}
1840
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001841
Guido van Rossum84a90321996-05-22 16:34:47 +00001842#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001843
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001844void
Fred Drake100814d2000-07-09 15:48:49 +00001845_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001846{
Victor Stinner9e00e802018-10-25 13:31:16 +02001847 if (_Py_tracemalloc_config.tracing) {
1848 _PyTraceMalloc_NewReference(op);
1849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 _Py_INC_REFTOTAL;
1851 op->ob_refcnt = 1;
1852 _Py_AddToAllObjects(op, 1);
1853 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001854}
1855
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001856void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001857_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001859#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001860 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001861#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (op->ob_refcnt < 0)
1863 Py_FatalError("UNREF negative refcnt");
1864 if (op == &refchain ||
1865 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1866 fprintf(stderr, "* ob\n");
1867 _PyObject_Dump(op);
1868 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1869 _PyObject_Dump(op->_ob_prev->_ob_next);
1870 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1871 _PyObject_Dump(op->_ob_next->_ob_prev);
1872 Py_FatalError("UNREF invalid object");
1873 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001874#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1876 if (p == op)
1877 break;
1878 }
1879 if (p == &refchain) /* Not found */
1880 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001881#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 op->_ob_next->_ob_prev = op->_ob_prev;
1883 op->_ob_prev->_ob_next = op->_ob_next;
1884 op->_ob_next = op->_ob_prev = NULL;
1885 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001886}
1887
Tim Peters269b2a62003-04-17 19:52:29 +00001888/* Print all live objects. Because PyObject_Print is called, the
1889 * interpreter must be in a healthy state.
1890 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001891void
Fred Drake100814d2000-07-09 15:48:49 +00001892_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 PyObject *op;
1895 fprintf(fp, "Remaining objects:\n");
1896 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001897 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", (void *)op, op->ob_refcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (PyObject_Print(op, fp, 0) != 0)
1899 PyErr_Clear();
1900 putc('\n', fp);
1901 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001902}
1903
Tim Peters269b2a62003-04-17 19:52:29 +00001904/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1905 * doesn't make any calls to the Python C API, so is always safe to call.
1906 */
1907void
1908_Py_PrintReferenceAddresses(FILE *fp)
1909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 PyObject *op;
1911 fprintf(fp, "Remaining object addresses:\n");
1912 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001913 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", (void *)op,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001915}
1916
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001917PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001918_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 int i, n;
1921 PyObject *t = NULL;
1922 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1925 return NULL;
1926 op = refchain._ob_next;
1927 res = PyList_New(0);
1928 if (res == NULL)
1929 return NULL;
1930 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1931 while (op == self || op == args || op == res || op == t ||
1932 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1933 op = op->_ob_next;
1934 if (op == &refchain)
1935 return res;
1936 }
1937 if (PyList_Append(res, op) < 0) {
1938 Py_DECREF(res);
1939 return NULL;
1940 }
1941 op = op->_ob_next;
1942 }
1943 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001944}
1945
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001946#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001947
Benjamin Petersonb173f782009-05-05 22:31:58 +00001948
Guido van Rossum84a90321996-05-22 16:34:47 +00001949/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001950Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001951
1952
David Malcolm49526f42012-06-22 14:55:41 -04001953void
1954_PyObject_DebugTypeStats(FILE *out)
1955{
1956 _PyCFunction_DebugMallocStats(out);
1957 _PyDict_DebugMallocStats(out);
1958 _PyFloat_DebugMallocStats(out);
1959 _PyFrame_DebugMallocStats(out);
1960 _PyList_DebugMallocStats(out);
1961 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001962 _PyTuple_DebugMallocStats(out);
1963}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001964
Guido van Rossum86610361998-04-10 22:32:46 +00001965/* These methods are used to control infinite recursion in repr, str, print,
1966 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00001967 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00001968 Py_ReprLeave() to avoid infinite recursion.
1969
1970 Py_ReprEnter() returns 0 the first time it is called for a particular
1971 object and 1 every time thereafter. It returns -1 if an exception
1972 occurred. Py_ReprLeave() has no return value.
1973
1974 See dictobject.c and listobject.c for examples of use.
1975*/
1976
Guido van Rossum86610361998-04-10 22:32:46 +00001977int
Fred Drake100814d2000-07-09 15:48:49 +00001978Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PyObject *dict;
1981 PyObject *list;
1982 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02001985 /* Ignore a missing thread-state, so that this function can be called
1986 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 if (dict == NULL)
1988 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001989 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001991 if (PyErr_Occurred()) {
1992 return -1;
1993 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 list = PyList_New(0);
1995 if (list == NULL)
1996 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001997 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 return -1;
1999 Py_DECREF(list);
2000 }
2001 i = PyList_GET_SIZE(list);
2002 while (--i >= 0) {
2003 if (PyList_GET_ITEM(list, i) == obj)
2004 return 1;
2005 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002006 if (PyList_Append(list, obj) < 0)
2007 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002009}
2010
2011void
Fred Drake100814d2000-07-09 15:48:49 +00002012Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 PyObject *dict;
2015 PyObject *list;
2016 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002017 PyObject *error_type, *error_value, *error_traceback;
2018
2019 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 dict = PyThreadState_GetDict();
2022 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002023 goto finally;
2024
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002025 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002027 goto finally;
2028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 i = PyList_GET_SIZE(list);
2030 /* Count backwards because we always expect obj to be list[-1] */
2031 while (--i >= 0) {
2032 if (PyList_GET_ITEM(list, i) == obj) {
2033 PyList_SetSlice(list, i, i + 1, NULL);
2034 break;
2035 }
2036 }
Victor Stinner1b634932013-07-16 22:24:44 +02002037
2038finally:
2039 /* ignore exceptions because there is no way to report them. */
2040 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002041}
Guido van Rossumd724b232000-03-13 16:01:29 +00002042
Tim Peters803526b2002-07-07 05:13:56 +00002043/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002044
Tim Peters803526b2002-07-07 05:13:56 +00002045/* Add op to the _PyTrash_delete_later list. Called when the current
2046 * call-stack depth gets large. op must be a currently untracked gc'ed
2047 * object, with refcount 0. Py_DECREF must already have been called on it.
2048 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002049void
Fred Drake100814d2000-07-09 15:48:49 +00002050_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002051{
Victor Stinner24702042018-10-26 17:16:37 +02002052 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2053 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2054 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002055 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002056 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002057}
2058
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002059/* The equivalent API, using per-thread state recursion info */
2060void
2061_PyTrash_thread_deposit_object(PyObject *op)
2062{
Victor Stinner50b48572018-11-01 01:51:40 +01002063 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002064 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2065 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2066 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002067 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002068 tstate->trash_delete_later = op;
2069}
2070
Tim Peters803526b2002-07-07 05:13:56 +00002071/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2072 * the call-stack unwinds again.
2073 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002074void
Fred Drake100814d2000-07-09 15:48:49 +00002075_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002076{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002077 while (_PyRuntime.gc.trash_delete_later) {
2078 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002080
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002081 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002082 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* Call the deallocator directly. This used to try to
2085 * fool Py_DECREF into calling it indirectly, but
2086 * Py_DECREF was already called on this object, and in
2087 * assorted non-release builds calling Py_DECREF again ends
2088 * up distorting allocation statistics.
2089 */
Victor Stinner24702042018-10-26 17:16:37 +02002090 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002091 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002093 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002095}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002096
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002097/* The equivalent API, using per-thread state recursion info */
2098void
2099_PyTrash_thread_destroy_chain(void)
2100{
Victor Stinner50b48572018-11-01 01:51:40 +01002101 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002102 /* We need to increase trash_delete_nesting here, otherwise,
2103 _PyTrash_thread_destroy_chain will be called recursively
2104 and then possibly crash. An example that may crash without
2105 increase:
2106 N = 500000 # need to be large enough
2107 ob = object()
2108 tups = [(ob,) for i in range(N)]
2109 for i in range(49):
2110 tups = [(tup,) for tup in tups]
2111 del tups
2112 */
2113 assert(tstate->trash_delete_nesting == 0);
2114 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002115 while (tstate->trash_delete_later) {
2116 PyObject *op = tstate->trash_delete_later;
2117 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2118
2119 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002120 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002121
2122 /* Call the deallocator directly. This used to try to
2123 * fool Py_DECREF into calling it indirectly, but
2124 * Py_DECREF was already called on this object, and in
2125 * assorted non-release builds calling Py_DECREF again ends
2126 * up distorting allocation statistics.
2127 */
Victor Stinner24702042018-10-26 17:16:37 +02002128 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002129 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002130 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002131 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002132 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002133}
2134
Victor Stinner626bff82018-10-25 17:31:10 +02002135
2136void
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002137_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002138 const char *file, int line, const char *function)
2139{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002140 fprintf(stderr, "%s:%d: ", file, line);
2141 if (function) {
2142 fprintf(stderr, "%s: ", function);
2143 }
Victor Stinner626bff82018-10-25 17:31:10 +02002144 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002145 if (expr) {
2146 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002147 }
2148 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002149 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002150 }
2151 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002152 if (msg) {
2153 fprintf(stderr, ": %s", msg);
2154 }
2155 fprintf(stderr, "\n");
2156 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002157
2158 if (obj == NULL) {
2159 fprintf(stderr, "<NULL object>\n");
2160 }
2161 else if (_PyObject_IsFreed(obj)) {
2162 /* It seems like the object memory has been freed:
2163 don't access it to prevent a segmentation fault. */
Victor Stinner0fc91ee2019-04-12 21:51:34 +02002164 fprintf(stderr, "<object: freed>\n");
2165 }
2166 else if (Py_TYPE(obj) == NULL) {
2167 fprintf(stderr, "<object: ob_type=NULL>\n");
2168 }
2169 else if (_PyObject_IsFreed((PyObject *)Py_TYPE(obj))) {
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002170 fprintf(stderr, "<object: freed type %p>\n", (void *)Py_TYPE(obj));
Victor Stinner626bff82018-10-25 17:31:10 +02002171 }
2172 else {
penguindustin96466302019-05-06 14:57:17 -04002173 /* Display the traceback where the object has been allocated.
Victor Stinner626bff82018-10-25 17:31:10 +02002174 Do it before dumping repr(obj), since repr() is more likely
2175 to crash than dumping the traceback. */
2176 void *ptr;
2177 PyTypeObject *type = Py_TYPE(obj);
2178 if (PyType_IS_GC(type)) {
2179 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2180 }
2181 else {
2182 ptr = (void *)obj;
2183 }
2184 _PyMem_DumpTraceback(fileno(stderr), ptr);
2185
2186 /* This might succeed or fail, but we're about to abort, so at least
2187 try to provide any extra info we can: */
2188 _PyObject_Dump(obj);
2189 }
2190 fflush(stderr);
2191
2192 Py_FatalError("_PyObject_AssertFailed");
2193}
2194
Victor Stinner3c09dca2018-10-30 14:48:26 +01002195
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002196#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002197
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002198void
2199_Py_Dealloc(PyObject *op)
2200{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002201 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2202#ifdef Py_TRACE_REFS
2203 _Py_ForgetReference(op);
2204#else
2205 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002206#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002207 (*dealloc)(op);
2208}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002209
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002210#ifdef __cplusplus
2211}
2212#endif