blob: d3a97f6c5bd47dac60c94ec7462c1713af19a945 [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 Stinner27e2d1f2018-11-01 00:52:28 +01005#include "pycore_state.h"
6#include "pycore_context.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00007#include "frameobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009#ifdef __cplusplus
10extern "C" {
11#endif
12
Victor Stinner626bff82018-10-25 17:31:10 +020013/* Defined in tracemalloc.c */
14extern void _PyMem_DumpTraceback(int fd, const void *ptr);
15
Victor Stinnerbd303c12013-11-07 23:07:29 +010016_Py_IDENTIFIER(Py_Repr);
17_Py_IDENTIFIER(__bytes__);
18_Py_IDENTIFIER(__dir__);
19_Py_IDENTIFIER(__isabstractmethod__);
20_Py_IDENTIFIER(builtins);
21
Tim Peters34592512002-07-11 06:23:50 +000022#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000023Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024
25Py_ssize_t
26_Py_GetRefTotal(void)
27{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 PyObject *o;
29 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020030 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 if (o != NULL)
32 total -= o->ob_refcnt;
33 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000034}
Nick Coghland6009512014-11-20 21:39:37 +100035
36void
37_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070038 fprintf(stderr,
39 "[%" PY_FORMAT_SIZE_T "d refs, "
40 "%" PY_FORMAT_SIZE_T "d blocks]\n",
41 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100042}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044
Guido van Rossum3f5da241990-12-20 15:06:42 +000045/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
46 These are used by the individual routines for object creation.
47 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000048
Tim Peters78be7992003-03-23 02:51:01 +000049#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000050/* Head of circular doubly-linked list of all objects. These are linked
51 * together via the _ob_prev and _ob_next members of a PyObject, which
52 * exist only in a Py_TRACE_REFS build.
53 */
Tim Peters78be7992003-03-23 02:51:01 +000054static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000055
Tim Peters7571a0f2003-03-23 17:52:28 +000056/* Insert op at the front of the list of all objects. If force is true,
57 * op is added even if _ob_prev and _ob_next are non-NULL already. If
58 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
59 * force should be true if and only if op points to freshly allocated,
60 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000061 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000062 * Note that objects are normally added to the list via _Py_NewReference,
63 * which is called by PyObject_Init. Not all objects are initialized that
64 * way, though; exceptions include statically allocated type objects, and
65 * statically allocated singletons (like Py_True and Py_None).
66 */
Tim Peters36eb4df2003-03-23 03:33:13 +000067void
Tim Peters7571a0f2003-03-23 17:52:28 +000068_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000069{
Tim Peters7571a0f2003-03-23 17:52:28 +000070#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 if (!force) {
72 /* If it's initialized memory, op must be in or out of
73 * the list unambiguously.
74 */
Victor Stinner24702042018-10-26 17:16:37 +020075 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 }
Tim Peters78be7992003-03-23 02:51:01 +000077#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (force || op->_ob_prev == NULL) {
79 op->_ob_next = refchain._ob_next;
80 op->_ob_prev = &refchain;
81 refchain._ob_next->_ob_prev = op;
82 refchain._ob_next = op;
83 }
Tim Peters7571a0f2003-03-23 17:52:28 +000084}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000086
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000087#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000088static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089/* All types are added to type_list, at least when
90 they get one object created. That makes them
91 immortal, which unfortunately contributes to
92 garbage itself. If unlist_types_without_objects
93 is set, they will be removed from the type_list
94 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +000095static int unlist_types_without_objects;
Pablo Galindo49c75a82018-10-28 15:02:17 +000096extern Py_ssize_t _Py_tuple_zero_allocs, _Py_fast_tuple_allocs;
97extern Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
98extern Py_ssize_t _Py_null_strings, _Py_one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000099void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000100_Py_dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000101{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200102 PyInterpreterState *interp = _PyInterpreterState_Get();
Eddie Elizondo745dc652018-02-21 20:55:18 -0800103 if (!interp->core_config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300104 return;
Victor Stinner25420fe2017-11-20 18:12:22 -0800105 }
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000106
Eddie Elizondo745dc652018-02-21 20:55:18 -0800107 PyTypeObject *tp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 for (tp = type_list; tp; tp = tp->tp_next)
109 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
110 "freed: %" PY_FORMAT_SIZE_T "d, "
111 "max in use: %" PY_FORMAT_SIZE_T "d\n",
112 tp->tp_name, tp->tp_allocs, tp->tp_frees,
113 tp->tp_maxalloc);
114 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
115 "empty: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000116 _Py_fast_tuple_allocs, _Py_tuple_zero_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
118 "neg: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000119 _Py_quick_int_allocs, _Py_quick_neg_int_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
121 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000122 _Py_null_strings, _Py_one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000123}
124
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000125PyObject *
Pablo Galindo49c75a82018-10-28 15:02:17 +0000126_Py_get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyTypeObject *tp;
129 PyObject *result;
130 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 result = PyList_New(0);
133 if (result == NULL)
134 return NULL;
135 for (tp = type_list; tp; tp = tp->tp_next) {
136 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
137 tp->tp_frees, tp->tp_maxalloc);
138 if (v == NULL) {
139 Py_DECREF(result);
140 return NULL;
141 }
142 if (PyList_Append(result, v) < 0) {
143 Py_DECREF(v);
144 Py_DECREF(result);
145 return NULL;
146 }
147 Py_DECREF(v);
148 }
149 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000150}
151
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000152void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000153_Py_inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
156 /* first time; insert in linked list */
157 if (tp->tp_next != NULL) /* sanity check */
Pablo Galindo49c75a82018-10-28 15:02:17 +0000158 Py_FatalError("XXX _Py_inc_count sanity check");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 if (type_list)
160 type_list->tp_prev = tp;
161 tp->tp_next = type_list;
162 /* Note that as of Python 2.2, heap-allocated type objects
163 * can go away, but this code requires that they stay alive
164 * until program exit. That's why we're careful with
165 * refcounts here. type_list gets a new reference to tp,
166 * while ownership of the reference type_list used to hold
167 * (if any) was transferred to tp->tp_next in the line above.
168 * tp is thus effectively immortal after this.
169 */
170 Py_INCREF(tp);
171 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000172#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 /* Also insert in the doubly-linked list of all objects,
174 * if not already there.
175 */
176 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
179 tp->tp_allocs++;
180 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
181 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000182}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183
Pablo Galindo49c75a82018-10-28 15:02:17 +0000184void _Py_dec_count(PyTypeObject *tp)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 tp->tp_frees++;
187 if (unlist_types_without_objects &&
188 tp->tp_allocs == tp->tp_frees) {
189 /* unlink the type from type_list */
190 if (tp->tp_prev)
191 tp->tp_prev->tp_next = tp->tp_next;
192 else
193 type_list = tp->tp_next;
194 if (tp->tp_next)
195 tp->tp_next->tp_prev = tp->tp_prev;
196 tp->tp_next = tp->tp_prev = NULL;
197 Py_DECREF(tp);
198 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000199}
200
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000201#endif
202
Tim Peters7c321a82002-07-09 02:57:01 +0000203#ifdef Py_REF_DEBUG
204/* Log a fatal error; doesn't return. */
205void
Victor Stinner18618e652018-10-25 17:28:11 +0200206_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000207{
Victor Stinner3ec9af72018-10-26 02:12:34 +0200208 _PyObject_AssertFailed(op, "object has negative ref count",
209 "op->ob_refcnt >= 0",
210 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000211}
212
213#endif /* Py_REF_DEBUG */
214
Thomas Heller1328b522004-04-22 17:23:49 +0000215void
216Py_IncRef(PyObject *o)
217{
218 Py_XINCREF(o);
219}
220
221void
222Py_DecRef(PyObject *o)
223{
224 Py_XDECREF(o);
225}
226
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000227PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000228PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (op == NULL)
231 return PyErr_NoMemory();
232 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
233 Py_TYPE(op) = tp;
234 _Py_NewReference(op);
235 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236}
237
Guido van Rossumb18618d2000-05-03 23:44:39 +0000238PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000239PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (op == NULL)
242 return (PyVarObject *) PyErr_NoMemory();
243 /* Any changes should be reflected in PyObject_INIT_VAR */
244 op->ob_size = size;
245 Py_TYPE(op) = tp;
246 _Py_NewReference((PyObject *)op);
247 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000248}
249
250PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000251_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 PyObject *op;
254 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
255 if (op == NULL)
256 return PyErr_NoMemory();
257 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000258}
259
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000260PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000261_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 PyVarObject *op;
264 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
265 op = (PyVarObject *) PyObject_MALLOC(size);
266 if (op == NULL)
267 return (PyVarObject *)PyErr_NoMemory();
268 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000269}
270
Antoine Pitrou796564c2013-07-30 19:59:21 +0200271void
272PyObject_CallFinalizer(PyObject *self)
273{
274 PyTypeObject *tp = Py_TYPE(self);
275
276 /* The former could happen on heaptypes created from the C API, e.g.
277 PyType_FromSpec(). */
278 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
279 tp->tp_finalize == NULL)
280 return;
281 /* tp_finalize should only be called once. */
282 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
283 return;
284
285 tp->tp_finalize(self);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900286 if (PyType_IS_GC(tp)) {
287 _PyGC_SET_FINALIZED(self);
288 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200289}
290
291int
292PyObject_CallFinalizerFromDealloc(PyObject *self)
293{
294 Py_ssize_t refcnt;
295
296 /* Temporarily resurrect the object. */
297 if (self->ob_refcnt != 0) {
298 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
299 "object with a non-zero refcount");
300 }
301 self->ob_refcnt = 1;
302
303 PyObject_CallFinalizer(self);
304
305 /* Undo the temporary resurrection; can't use DECREF here, it would
306 * cause a recursive call.
307 */
Victor Stinner24702042018-10-26 17:16:37 +0200308 _PyObject_ASSERT_WITH_MSG(self,
309 self->ob_refcnt > 0,
310 "refcount is too small");
Antoine Pitrou796564c2013-07-30 19:59:21 +0200311 if (--self->ob_refcnt == 0)
312 return 0; /* this is the normal path out */
313
314 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
315 * never happened.
316 */
317 refcnt = self->ob_refcnt;
318 _Py_NewReference(self);
319 self->ob_refcnt = refcnt;
320
Victor Stinner24702042018-10-26 17:16:37 +0200321 _PyObject_ASSERT(self,
322 (!PyType_IS_GC(Py_TYPE(self))
323 || _PyObject_GC_IS_TRACKED(self)));
Antoine Pitrou796564c2013-07-30 19:59:21 +0200324 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
325 * we need to undo that. */
326 _Py_DEC_REFTOTAL;
327 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
328 * chain, so no more to do there.
329 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
330 * _Py_NewReference bumped tp_allocs: both of those need to be
331 * undone.
332 */
333#ifdef COUNT_ALLOCS
334 --Py_TYPE(self)->tp_frees;
335 --Py_TYPE(self)->tp_allocs;
336#endif
337 return -1;
338}
339
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000340int
341PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (PyErr_CheckSignals())
345 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000346#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (PyOS_CheckStack()) {
348 PyErr_SetString(PyExc_MemoryError, "stack overflow");
349 return -1;
350 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000351#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 clearerr(fp); /* Clear any previous error condition */
353 if (op == NULL) {
354 Py_BEGIN_ALLOW_THREADS
355 fprintf(fp, "<nil>");
356 Py_END_ALLOW_THREADS
357 }
358 else {
Victor Stinner3ec9af72018-10-26 02:12:34 +0200359 if (op->ob_refcnt <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 /* XXX(twouters) cast refcount to long until %zd is
361 universally available */
362 Py_BEGIN_ALLOW_THREADS
363 fprintf(fp, "<refcnt %ld at %p>",
364 (long)op->ob_refcnt, op);
365 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200366 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 else {
368 PyObject *s;
369 if (flags & Py_PRINT_RAW)
370 s = PyObject_Str(op);
371 else
372 s = PyObject_Repr(op);
373 if (s == NULL)
374 ret = -1;
375 else if (PyBytes_Check(s)) {
376 fwrite(PyBytes_AS_STRING(s), 1,
377 PyBytes_GET_SIZE(s), fp);
378 }
379 else if (PyUnicode_Check(s)) {
380 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200381 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600382 if (t == NULL) {
383 ret = -1;
384 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 else {
386 fwrite(PyBytes_AS_STRING(t), 1,
387 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000388 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 }
390 }
391 else {
392 PyErr_Format(PyExc_TypeError,
393 "str() or repr() returned '%.100s'",
394 s->ob_type->tp_name);
395 ret = -1;
396 }
397 Py_XDECREF(s);
398 }
399 }
400 if (ret == 0) {
401 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300402 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 clearerr(fp);
404 ret = -1;
405 }
406 }
407 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408}
409
Guido van Rossum38938152006-08-21 23:36:26 +0000410/* For debugging convenience. Set a breakpoint here and call it from your DLL */
411void
Thomas Woutersb2137042007-02-01 18:02:27 +0000412_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000413{
414}
415
Neal Norwitz1a997502003-01-13 20:13:12 +0000416
Victor Stinner82af0b62018-10-23 17:39:40 +0200417/* Heuristic checking if the object memory has been deallocated.
418 Rely on the debug hooks on Python memory allocators which fills the memory
419 with DEADBYTE (0xDB) when memory is deallocated.
420
421 The function can be used to prevent segmentation fault on dereferencing
422 pointers like 0xdbdbdbdbdbdbdbdb. Such pointer is very unlikely to be mapped
423 in memory. */
424int
425_PyObject_IsFreed(PyObject *op)
426{
427 int freed = _PyMem_IsFreed(&op->ob_type, sizeof(op->ob_type));
428 /* ignore op->ob_ref: the value can have be modified
429 by Py_INCREF() and Py_DECREF(). */
430#ifdef Py_TRACE_REFS
431 freed &= _PyMem_IsFreed(&op->_ob_next, sizeof(op->_ob_next));
432 freed &= _PyMem_IsFreed(&op->_ob_prev, sizeof(op->_ob_prev));
433#endif
434 return freed;
435}
436
437
Barry Warsaw9bf16442001-01-23 16:24:35 +0000438/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000439void
440_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000441{
Victor Stinner82af0b62018-10-23 17:39:40 +0200442 if (op == NULL) {
443 fprintf(stderr, "<NULL object>\n");
444 fflush(stderr);
445 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200447
448 if (_PyObject_IsFreed(op)) {
449 /* It seems like the object memory has been freed:
450 don't access it to prevent a segmentation fault. */
451 fprintf(stderr, "<freed object>\n");
452 }
453
454 PyGILState_STATE gil;
455 PyObject *error_type, *error_value, *error_traceback;
456
457 fprintf(stderr, "object : ");
458 fflush(stderr);
459 gil = PyGILState_Ensure();
460
461 PyErr_Fetch(&error_type, &error_value, &error_traceback);
462 (void)PyObject_Print(op, stderr, 0);
463 fflush(stderr);
464 PyErr_Restore(error_type, error_value, error_traceback);
465
466 PyGILState_Release(gil);
467 /* XXX(twouters) cast refcount to long until %zd is
468 universally available */
469 fprintf(stderr, "\n"
470 "type : %s\n"
471 "refcount: %ld\n"
472 "address : %p\n",
473 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
474 (long)op->ob_refcnt,
475 op);
476 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000477}
Barry Warsaw903138f2001-01-23 16:33:18 +0000478
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000480PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 PyObject *res;
483 if (PyErr_CheckSignals())
484 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000485#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 if (PyOS_CheckStack()) {
487 PyErr_SetString(PyExc_MemoryError, "stack overflow");
488 return NULL;
489 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000490#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (v == NULL)
492 return PyUnicode_FromString("<NULL>");
493 if (Py_TYPE(v)->tp_repr == NULL)
494 return PyUnicode_FromFormat("<%s object at %p>",
495 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200496
497#ifdef Py_DEBUG
498 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100499 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000500 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200501 assert(!PyErr_Occurred());
502#endif
503
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200504 /* It is possible for a type to have a tp_repr representation that loops
505 infinitely. */
506 if (Py_EnterRecursiveCall(" while getting the repr of an object"))
507 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 res = (*v->ob_type->tp_repr)(v);
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200509 Py_LeaveRecursiveCall();
Victor Stinner0a54cf12011-12-01 03:22:44 +0100510 if (res == NULL)
511 return NULL;
512 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PyErr_Format(PyExc_TypeError,
514 "__repr__ returned non-string (type %.200s)",
515 res->ob_type->tp_name);
516 Py_DECREF(res);
517 return NULL;
518 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100519#ifndef Py_DEBUG
520 if (PyUnicode_READY(res) < 0)
521 return NULL;
522#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000524}
525
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000527PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 PyObject *res;
530 if (PyErr_CheckSignals())
531 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000532#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (PyOS_CheckStack()) {
534 PyErr_SetString(PyExc_MemoryError, "stack overflow");
535 return NULL;
536 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000537#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (v == NULL)
539 return PyUnicode_FromString("<NULL>");
540 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100541#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100542 if (PyUnicode_READY(v) < 0)
543 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100544#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 Py_INCREF(v);
546 return v;
547 }
548 if (Py_TYPE(v)->tp_str == NULL)
549 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000550
Victor Stinner33824f62013-08-26 14:05:19 +0200551#ifdef Py_DEBUG
552 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100553 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000554 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200555 assert(!PyErr_Occurred());
556#endif
557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 /* It is possible for a type to have a tp_str representation that loops
559 infinitely. */
560 if (Py_EnterRecursiveCall(" while getting the str of an object"))
561 return NULL;
562 res = (*Py_TYPE(v)->tp_str)(v);
563 Py_LeaveRecursiveCall();
564 if (res == NULL)
565 return NULL;
566 if (!PyUnicode_Check(res)) {
567 PyErr_Format(PyExc_TypeError,
568 "__str__ returned non-string (type %.200s)",
569 Py_TYPE(res)->tp_name);
570 Py_DECREF(res);
571 return NULL;
572 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100573#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100574 if (PyUnicode_READY(res) < 0)
575 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100576#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100577 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000579}
580
Georg Brandl559e5d72008-06-11 18:37:52 +0000581PyObject *
582PyObject_ASCII(PyObject *v)
583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 repr = PyObject_Repr(v);
587 if (repr == NULL)
588 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000589
Victor Stinneraf037572013-04-14 18:44:10 +0200590 if (PyUnicode_IS_ASCII(repr))
591 return repr;
592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200594 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 Py_DECREF(repr);
596 if (ascii == NULL)
597 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 res = PyUnicode_DecodeASCII(
600 PyBytes_AS_STRING(ascii),
601 PyBytes_GET_SIZE(ascii),
602 NULL);
603
604 Py_DECREF(ascii);
605 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000606}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000607
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000608PyObject *
609PyObject_Bytes(PyObject *v)
610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (v == NULL)
614 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (PyBytes_CheckExact(v)) {
617 Py_INCREF(v);
618 return v;
619 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000620
Benjamin Petersonce798522012-01-22 11:24:29 -0500621 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100623 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 Py_DECREF(func);
625 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000626 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000628 PyErr_Format(PyExc_TypeError,
629 "__bytes__ returned non-bytes (type %.200s)",
630 Py_TYPE(result)->tp_name);
631 Py_DECREF(result);
632 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 }
634 return result;
635 }
636 else if (PyErr_Occurred())
637 return NULL;
638 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000639}
640
Mark Dickinsonc008a172009-02-01 13:59:22 +0000641/* For Python 3.0.1 and later, the old three-way comparison has been
642 completely removed in favour of rich comparisons. PyObject_Compare() and
643 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000644 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000645 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000646
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000647 See (*) below for practical amendments.
648
Mark Dickinsonc008a172009-02-01 13:59:22 +0000649 tp_richcompare gets called with a first argument of the appropriate type
650 and a second object of an arbitrary type. We never do any kind of
651 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000652
Mark Dickinsonc008a172009-02-01 13:59:22 +0000653 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000654
655 NULL if an exception occurred
656 NotImplemented if the requested comparison is not implemented
657 any other false value if the requested comparison is false
658 any other true value if the requested comparison is true
659
660 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
661 NotImplemented.
662
663 (*) Practical amendments:
664
665 - If rich comparison returns NotImplemented, == and != are decided by
666 comparing the object pointer (i.e. falling back to the base object
667 implementation).
668
Guido van Rossuma4073002002-05-31 20:03:54 +0000669*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000670
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000671/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000672int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000673
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200674static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000675
676/* Perform a rich comparison, raising TypeError when the requested comparison
677 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000678static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000679do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 richcmpfunc f;
682 PyObject *res;
683 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 if (v->ob_type != w->ob_type &&
686 PyType_IsSubtype(w->ob_type, v->ob_type) &&
687 (f = w->ob_type->tp_richcompare) != NULL) {
688 checked_reverse_op = 1;
689 res = (*f)(w, v, _Py_SwappedOp[op]);
690 if (res != Py_NotImplemented)
691 return res;
692 Py_DECREF(res);
693 }
694 if ((f = v->ob_type->tp_richcompare) != NULL) {
695 res = (*f)(v, w, op);
696 if (res != Py_NotImplemented)
697 return res;
698 Py_DECREF(res);
699 }
700 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
701 res = (*f)(w, v, _Py_SwappedOp[op]);
702 if (res != Py_NotImplemented)
703 return res;
704 Py_DECREF(res);
705 }
706 /* If neither object implements it, provide a sensible default
707 for == and !=, but raise an exception for ordering. */
708 switch (op) {
709 case Py_EQ:
710 res = (v == w) ? Py_True : Py_False;
711 break;
712 case Py_NE:
713 res = (v != w) ? Py_True : Py_False;
714 break;
715 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyErr_Format(PyExc_TypeError,
Victor Stinner91108f02015-10-14 18:25:31 +0200717 "'%s' not supported between instances of '%.100s' and '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 opstrings[op],
Victor Stinner91108f02015-10-14 18:25:31 +0200719 v->ob_type->tp_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 w->ob_type->tp_name);
721 return NULL;
722 }
723 Py_INCREF(res);
724 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000725}
726
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000727/* Perform a rich comparison with object result. This wraps do_richcompare()
728 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000729
Guido van Rossume797ec12001-01-17 15:24:28 +0000730PyObject *
731PyObject_RichCompare(PyObject *v, PyObject *w, int op)
732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 assert(Py_LT <= op && op <= Py_GE);
736 if (v == NULL || w == NULL) {
737 if (!PyErr_Occurred())
738 PyErr_BadInternalCall();
739 return NULL;
740 }
741 if (Py_EnterRecursiveCall(" in comparison"))
742 return NULL;
743 res = do_richcompare(v, w, op);
744 Py_LeaveRecursiveCall();
745 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000746}
747
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000748/* Perform a rich comparison with integer result. This wraps
749 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000750int
751PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyObject *res;
754 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 /* Quick result when objects are the same.
757 Guarantees that identity implies equality. */
758 if (v == w) {
759 if (op == Py_EQ)
760 return 1;
761 else if (op == Py_NE)
762 return 0;
763 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 res = PyObject_RichCompare(v, w, op);
766 if (res == NULL)
767 return -1;
768 if (PyBool_Check(res))
769 ok = (res == Py_True);
770 else
771 ok = PyObject_IsTrue(res);
772 Py_DECREF(res);
773 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000774}
Fred Drake13634cf2000-06-29 19:17:04 +0000775
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100776Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000777PyObject_HashNotImplemented(PyObject *v)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
780 Py_TYPE(v)->tp_name);
781 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000782}
Fred Drake13634cf2000-06-29 19:17:04 +0000783
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000784Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000785PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyTypeObject *tp = Py_TYPE(v);
788 if (tp->tp_hash != NULL)
789 return (*tp->tp_hash)(v);
790 /* To keep to the general practice that inheriting
791 * solely from object in C code should work without
792 * an explicit call to PyType_Ready, we implicitly call
793 * PyType_Ready here and then check the tp_hash slot again
794 */
795 if (tp->tp_dict == NULL) {
796 if (PyType_Ready(tp) < 0)
797 return -1;
798 if (tp->tp_hash != NULL)
799 return (*tp->tp_hash)(v);
800 }
801 /* Otherwise, the object can't be hashed */
802 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000803}
804
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000805PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000806PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (Py_TYPE(v)->tp_getattr != NULL)
811 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900812 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (w == NULL)
814 return NULL;
815 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100816 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000818}
819
820int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000821PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 PyObject *res = PyObject_GetAttrString(v, name);
824 if (res != NULL) {
825 Py_DECREF(res);
826 return 1;
827 }
828 PyErr_Clear();
829 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000830}
831
832int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000833PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *s;
836 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (Py_TYPE(v)->tp_setattr != NULL)
839 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
840 s = PyUnicode_InternFromString(name);
841 if (s == NULL)
842 return -1;
843 res = PyObject_SetAttr(v, s, w);
844 Py_XDECREF(s);
845 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000846}
847
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500848int
849_PyObject_IsAbstract(PyObject *obj)
850{
851 int res;
852 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500853
854 if (obj == NULL)
855 return 0;
856
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200857 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
858 if (res > 0) {
859 res = PyObject_IsTrue(isabstract);
860 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500861 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500862 return res;
863}
864
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000865PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200866_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
867{
868 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100869 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200870 if (!oname)
871 return NULL;
872 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200873 return result;
874}
875
876int
877_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
878{
879 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100880 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200881 if (!oname)
882 return -1;
883 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200884 return result;
885}
886
887int
888_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
889{
890 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100891 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200892 if (!oname)
893 return -1;
894 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200895 return result;
896}
897
898PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000899PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (!PyUnicode_Check(name)) {
904 PyErr_Format(PyExc_TypeError,
905 "attribute name must be string, not '%.200s'",
906 name->ob_type->tp_name);
907 return NULL;
908 }
909 if (tp->tp_getattro != NULL)
910 return (*tp->tp_getattro)(v, name);
911 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200912 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (name_str == NULL)
914 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200915 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 }
917 PyErr_Format(PyExc_AttributeError,
918 "'%.50s' object has no attribute '%U'",
919 tp->tp_name, name);
920 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000921}
922
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200923int
924_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900925{
926 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900927
928 if (!PyUnicode_Check(name)) {
929 PyErr_Format(PyExc_TypeError,
930 "attribute name must be string, not '%.200s'",
931 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200932 *result = NULL;
933 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900934 }
935
936 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200937 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
938 if (*result != NULL) {
939 return 1;
940 }
941 if (PyErr_Occurred()) {
942 return -1;
943 }
944 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900945 }
946 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200947 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900948 }
949 else if (tp->tp_getattr != NULL) {
950 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200951 if (name_str == NULL) {
952 *result = NULL;
953 return -1;
954 }
955 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900956 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900957 else {
958 *result = NULL;
959 return 0;
960 }
961
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200962 if (*result != NULL) {
963 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900964 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200965 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
966 return -1;
967 }
968 PyErr_Clear();
969 return 0;
970}
971
972int
973_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
974{
975 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
976 if (!oname) {
977 *result = NULL;
978 return -1;
979 }
980 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +0900981}
982
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000983int
Fred Drake100814d2000-07-09 15:48:49 +0000984PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000985{
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200986 PyObject *res;
987 if (_PyObject_LookupAttr(v, name, &res) < 0) {
988 PyErr_Clear();
989 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200991 if (res == NULL) {
992 return 0;
993 }
994 Py_DECREF(res);
995 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000996}
997
998int
Fred Drake100814d2000-07-09 15:48:49 +0000999PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 PyTypeObject *tp = Py_TYPE(v);
1002 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (!PyUnicode_Check(name)) {
1005 PyErr_Format(PyExc_TypeError,
1006 "attribute name must be string, not '%.200s'",
1007 name->ob_type->tp_name);
1008 return -1;
1009 }
1010 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyUnicode_InternInPlace(&name);
1013 if (tp->tp_setattro != NULL) {
1014 err = (*tp->tp_setattro)(v, name, value);
1015 Py_DECREF(name);
1016 return err;
1017 }
1018 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001019 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if (name_str == NULL)
1021 return -1;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001022 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 Py_DECREF(name);
1024 return err;
1025 }
1026 Py_DECREF(name);
Victor Stinner24702042018-10-26 17:16:37 +02001027 _PyObject_ASSERT(name, name->ob_refcnt >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1029 PyErr_Format(PyExc_TypeError,
1030 "'%.100s' object has no attributes "
1031 "(%s .%U)",
1032 tp->tp_name,
1033 value==NULL ? "del" : "assign to",
1034 name);
1035 else
1036 PyErr_Format(PyExc_TypeError,
1037 "'%.100s' object has only read-only attributes "
1038 "(%s .%U)",
1039 tp->tp_name,
1040 value==NULL ? "del" : "assign to",
1041 name);
1042 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001043}
1044
1045/* Helper to get a pointer to an object's __dict__ slot, if any */
1046
1047PyObject **
1048_PyObject_GetDictPtr(PyObject *obj)
1049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 Py_ssize_t dictoffset;
1051 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 dictoffset = tp->tp_dictoffset;
1054 if (dictoffset == 0)
1055 return NULL;
1056 if (dictoffset < 0) {
1057 Py_ssize_t tsize;
1058 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 tsize = ((PyVarObject *)obj)->ob_size;
1061 if (tsize < 0)
1062 tsize = -tsize;
1063 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001066 _PyObject_ASSERT(obj, dictoffset > 0);
1067 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 }
1069 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001070}
1071
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001073PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 Py_INCREF(obj);
1076 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001077}
1078
Antoine Pitroua7013882012-04-05 00:04:20 +02001079/* Convenience function to get a builtin from its name */
1080PyObject *
1081_PyObject_GetBuiltin(const char *name)
1082{
Victor Stinner53e9ec42013-11-07 00:43:05 +01001083 PyObject *mod_name, *mod, *attr;
1084
Victor Stinnerbd303c12013-11-07 23:07:29 +01001085 mod_name = _PyUnicode_FromId(&PyId_builtins); /* borrowed */
Victor Stinner53e9ec42013-11-07 00:43:05 +01001086 if (mod_name == NULL)
1087 return NULL;
1088 mod = PyImport_Import(mod_name);
Antoine Pitroua7013882012-04-05 00:04:20 +02001089 if (mod == NULL)
1090 return NULL;
1091 attr = PyObject_GetAttrString(mod, name);
1092 Py_DECREF(mod);
1093 return attr;
1094}
1095
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001096/* Helper used when the __next__ method is removed from a type:
1097 tp_iternext is never NULL and can be safely called without checking
1098 on every iteration.
1099 */
1100
1101PyObject *
1102_PyObject_NextNotImplemented(PyObject *self)
1103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 PyErr_Format(PyExc_TypeError,
1105 "'%.200s' object is not iterable",
1106 Py_TYPE(self)->tp_name);
1107 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001108}
1109
Yury Selivanovf2392132016-12-13 19:03:51 -05001110
1111/* Specialized version of _PyObject_GenericGetAttrWithDict
1112 specifically for the LOAD_METHOD opcode.
1113
1114 Return 1 if a method is found, 0 if it's a regular attribute
1115 from __dict__ or something returned by using a descriptor
1116 protocol.
1117
1118 `method` will point to the resolved attribute or NULL. In the
1119 latter case, an error will be set.
1120*/
1121int
1122_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1123{
1124 PyTypeObject *tp = Py_TYPE(obj);
1125 PyObject *descr;
1126 descrgetfunc f = NULL;
1127 PyObject **dictptr, *dict;
1128 PyObject *attr;
1129 int meth_found = 0;
1130
1131 assert(*method == NULL);
1132
1133 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1134 || !PyUnicode_Check(name)) {
1135 *method = PyObject_GetAttr(obj, name);
1136 return 0;
1137 }
1138
1139 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1140 return 0;
1141
1142 descr = _PyType_Lookup(tp, name);
1143 if (descr != NULL) {
1144 Py_INCREF(descr);
INADA Naoki5566bbb2017-02-03 07:43:03 +09001145 if (PyFunction_Check(descr) ||
1146 (Py_TYPE(descr) == &PyMethodDescr_Type)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001147 meth_found = 1;
1148 } else {
1149 f = descr->ob_type->tp_descr_get;
1150 if (f != NULL && PyDescr_IsData(descr)) {
1151 *method = f(descr, obj, (PyObject *)obj->ob_type);
1152 Py_DECREF(descr);
1153 return 0;
1154 }
1155 }
1156 }
1157
1158 dictptr = _PyObject_GetDictPtr(obj);
1159 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1160 Py_INCREF(dict);
1161 attr = PyDict_GetItem(dict, name);
1162 if (attr != NULL) {
1163 Py_INCREF(attr);
1164 *method = attr;
1165 Py_DECREF(dict);
1166 Py_XDECREF(descr);
1167 return 0;
1168 }
1169 Py_DECREF(dict);
1170 }
1171
1172 if (meth_found) {
1173 *method = descr;
1174 return 1;
1175 }
1176
1177 if (f != NULL) {
1178 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1179 Py_DECREF(descr);
1180 return 0;
1181 }
1182
1183 if (descr != NULL) {
1184 *method = descr;
1185 return 0;
1186 }
1187
1188 PyErr_Format(PyExc_AttributeError,
1189 "'%.50s' object has no attribute '%U'",
1190 tp->tp_name, name);
1191 return 0;
1192}
1193
1194/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001195
Raymond Hettinger01538262003-03-17 08:24:35 +00001196PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001197_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1198 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001199{
Yury Selivanovf2392132016-12-13 19:03:51 -05001200 /* Make sure the logic of _PyObject_GetMethod is in sync with
1201 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001202
1203 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001204 */
1205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 PyTypeObject *tp = Py_TYPE(obj);
1207 PyObject *descr = NULL;
1208 PyObject *res = NULL;
1209 descrgetfunc f;
1210 Py_ssize_t dictoffset;
1211 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (!PyUnicode_Check(name)){
1214 PyErr_Format(PyExc_TypeError,
1215 "attribute name must be string, not '%.200s'",
1216 name->ob_type->tp_name);
1217 return NULL;
1218 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001219 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 if (tp->tp_dict == NULL) {
1222 if (PyType_Ready(tp) < 0)
1223 goto done;
1224 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 f = NULL;
1229 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001230 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 f = descr->ob_type->tp_descr_get;
1232 if (f != NULL && PyDescr_IsData(descr)) {
1233 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001234 if (res == NULL && suppress &&
1235 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1236 PyErr_Clear();
1237 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 goto done;
1239 }
1240 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001241
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001242 if (dict == NULL) {
1243 /* Inline _PyObject_GetDictPtr */
1244 dictoffset = tp->tp_dictoffset;
1245 if (dictoffset != 0) {
1246 if (dictoffset < 0) {
1247 Py_ssize_t tsize;
1248 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001249
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001250 tsize = ((PyVarObject *)obj)->ob_size;
1251 if (tsize < 0)
1252 tsize = -tsize;
1253 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001254 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001255
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001256 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001257 _PyObject_ASSERT(obj, dictoffset > 0);
1258 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001260 dictptr = (PyObject **) ((char *)obj + dictoffset);
1261 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 }
1263 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001264 if (dict != NULL) {
1265 Py_INCREF(dict);
1266 res = PyDict_GetItem(dict, name);
1267 if (res != NULL) {
1268 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001269 Py_DECREF(dict);
1270 goto done;
1271 }
1272 Py_DECREF(dict);
1273 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (f != NULL) {
1276 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001277 if (res == NULL && suppress &&
1278 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1279 PyErr_Clear();
1280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 goto done;
1282 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (descr != NULL) {
1285 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001286 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 goto done;
1288 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001289
INADA Naoki378edee2018-01-16 20:52:41 +09001290 if (!suppress) {
1291 PyErr_Format(PyExc_AttributeError,
1292 "'%.50s' object has no attribute '%U'",
1293 tp->tp_name, name);
1294 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001295 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001296 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 Py_DECREF(name);
1298 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299}
1300
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001301PyObject *
1302PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1303{
INADA Naoki378edee2018-01-16 20:52:41 +09001304 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001305}
1306
Tim Peters6d6c1a32001-08-02 04:15:00 +00001307int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001308_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1309 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 PyTypeObject *tp = Py_TYPE(obj);
1312 PyObject *descr;
1313 descrsetfunc f;
1314 PyObject **dictptr;
1315 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (!PyUnicode_Check(name)){
1318 PyErr_Format(PyExc_TypeError,
1319 "attribute name must be string, not '%.200s'",
1320 name->ob_type->tp_name);
1321 return -1;
1322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001323
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001324 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1325 return -1;
1326
1327 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001332 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001334 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 res = f(descr, obj, value);
1336 goto done;
1337 }
1338 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001339
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001340 if (dict == NULL) {
1341 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001342 if (dictptr == NULL) {
1343 if (descr == NULL) {
1344 PyErr_Format(PyExc_AttributeError,
1345 "'%.100s' object has no attribute '%U'",
1346 tp->tp_name, name);
1347 }
1348 else {
1349 PyErr_Format(PyExc_AttributeError,
1350 "'%.50s' object attribute '%U' is read-only",
1351 tp->tp_name, name);
1352 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001353 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001355 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001356 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001357 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001358 Py_INCREF(dict);
1359 if (value == NULL)
1360 res = PyDict_DelItem(dict, name);
1361 else
1362 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001363 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001365 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1366 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001367
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001368 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001369 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 Py_DECREF(name);
1371 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001372}
1373
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001374int
1375PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1376{
1377 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1378}
1379
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001380int
1381PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1382{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001383 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001384 if (dictptr == NULL) {
1385 PyErr_SetString(PyExc_AttributeError,
1386 "This object has no __dict__");
1387 return -1;
1388 }
1389 if (value == NULL) {
1390 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1391 return -1;
1392 }
1393 if (!PyDict_Check(value)) {
1394 PyErr_Format(PyExc_TypeError,
1395 "__dict__ must be set to a dictionary, "
1396 "not a '%.200s'", Py_TYPE(value)->tp_name);
1397 return -1;
1398 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001399 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001400 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001401 return 0;
1402}
1403
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001404
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001405/* Test a value used as condition, e.g., in a for or if statement.
1406 Return -1 if an error occurred */
1407
1408int
Fred Drake100814d2000-07-09 15:48:49 +00001409PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 Py_ssize_t res;
1412 if (v == Py_True)
1413 return 1;
1414 if (v == Py_False)
1415 return 0;
1416 if (v == Py_None)
1417 return 0;
1418 else if (v->ob_type->tp_as_number != NULL &&
1419 v->ob_type->tp_as_number->nb_bool != NULL)
1420 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1421 else if (v->ob_type->tp_as_mapping != NULL &&
1422 v->ob_type->tp_as_mapping->mp_length != NULL)
1423 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1424 else if (v->ob_type->tp_as_sequence != NULL &&
1425 v->ob_type->tp_as_sequence->sq_length != NULL)
1426 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1427 else
1428 return 1;
1429 /* if it is negative, it should be either -1 or -2 */
1430 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001431}
1432
Tim Peters803526b2002-07-07 05:13:56 +00001433/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001434 Return -1 if an error occurred */
1435
1436int
Fred Drake100814d2000-07-09 15:48:49 +00001437PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 int res;
1440 res = PyObject_IsTrue(v);
1441 if (res < 0)
1442 return res;
1443 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001444}
1445
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001446/* Test whether an object can be called */
1447
1448int
Fred Drake100814d2000-07-09 15:48:49 +00001449PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (x == NULL)
1452 return 0;
1453 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001454}
1455
Tim Peters7eea37e2001-09-04 22:08:56 +00001456
Georg Brandle32b4222007-03-10 22:13:27 +00001457/* Helper for PyObject_Dir without arguments: returns the local scope. */
1458static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001459_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001462 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001463
Victor Stinner41bb43a2013-10-29 01:19:37 +01001464 locals = PyEval_GetLocals();
1465 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 names = PyMapping_Keys(locals);
1469 if (!names)
1470 return NULL;
1471 if (!PyList_Check(names)) {
1472 PyErr_Format(PyExc_TypeError,
1473 "dir(): expected keys() of locals to be a list, "
1474 "not '%.200s'", Py_TYPE(names)->tp_name);
1475 Py_DECREF(names);
1476 return NULL;
1477 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001478 if (PyList_Sort(names)) {
1479 Py_DECREF(names);
1480 return NULL;
1481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 /* the locals don't need to be DECREF'd */
1483 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001484}
1485
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001486/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001487static PyObject *
1488_dir_object(PyObject *obj)
1489{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001490 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001491 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001492
Victor Stinner24702042018-10-26 17:16:37 +02001493 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001495 if (!PyErr_Occurred())
1496 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1497 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001499 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001500 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001501 Py_DECREF(dirfunc);
1502 if (result == NULL)
1503 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001504 /* return sorted(result) */
1505 sorted = PySequence_List(result);
1506 Py_DECREF(result);
1507 if (sorted == NULL)
1508 return NULL;
1509 if (PyList_Sort(sorted)) {
1510 Py_DECREF(sorted);
1511 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001513 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001514}
1515
1516/* Implementation of dir() -- if obj is NULL, returns the names in the current
1517 (local) scope. Otherwise, performs introspection of the object: returns a
1518 sorted list of attribute names (supposedly) accessible from the object
1519*/
1520PyObject *
1521PyObject_Dir(PyObject *obj)
1522{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001523 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001524}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001525
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001526/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001527None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001528There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001529so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001530*/
1531
Guido van Rossum0c182a11992-03-27 17:26:13 +00001532/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001533static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001534none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001537}
1538
Barry Warsaw9bf16442001-01-23 16:24:35 +00001539/* ARGUSED */
1540static void
Tim Peters803526b2002-07-07 05:13:56 +00001541none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 /* This should never get called, but we also don't want to SEGV if
1544 * we accidentally decref None out of existence.
1545 */
1546 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001547}
1548
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001549static PyObject *
1550none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1551{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001552 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001553 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1554 return NULL;
1555 }
1556 Py_RETURN_NONE;
1557}
1558
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001559static int
1560none_bool(PyObject *v)
1561{
1562 return 0;
1563}
1564
1565static PyNumberMethods none_as_number = {
1566 0, /* nb_add */
1567 0, /* nb_subtract */
1568 0, /* nb_multiply */
1569 0, /* nb_remainder */
1570 0, /* nb_divmod */
1571 0, /* nb_power */
1572 0, /* nb_negative */
1573 0, /* nb_positive */
1574 0, /* nb_absolute */
1575 (inquiry)none_bool, /* nb_bool */
1576 0, /* nb_invert */
1577 0, /* nb_lshift */
1578 0, /* nb_rshift */
1579 0, /* nb_and */
1580 0, /* nb_xor */
1581 0, /* nb_or */
1582 0, /* nb_int */
1583 0, /* nb_reserved */
1584 0, /* nb_float */
1585 0, /* nb_inplace_add */
1586 0, /* nb_inplace_subtract */
1587 0, /* nb_inplace_multiply */
1588 0, /* nb_inplace_remainder */
1589 0, /* nb_inplace_power */
1590 0, /* nb_inplace_lshift */
1591 0, /* nb_inplace_rshift */
1592 0, /* nb_inplace_and */
1593 0, /* nb_inplace_xor */
1594 0, /* nb_inplace_or */
1595 0, /* nb_floor_divide */
1596 0, /* nb_true_divide */
1597 0, /* nb_inplace_floor_divide */
1598 0, /* nb_inplace_true_divide */
1599 0, /* nb_index */
1600};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001601
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001602PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1604 "NoneType",
1605 0,
1606 0,
1607 none_dealloc, /*tp_dealloc*/ /*never called*/
1608 0, /*tp_print*/
1609 0, /*tp_getattr*/
1610 0, /*tp_setattr*/
1611 0, /*tp_reserved*/
1612 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001613 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 0, /*tp_as_sequence*/
1615 0, /*tp_as_mapping*/
1616 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001617 0, /*tp_call */
1618 0, /*tp_str */
1619 0, /*tp_getattro */
1620 0, /*tp_setattro */
1621 0, /*tp_as_buffer */
1622 Py_TPFLAGS_DEFAULT, /*tp_flags */
1623 0, /*tp_doc */
1624 0, /*tp_traverse */
1625 0, /*tp_clear */
1626 0, /*tp_richcompare */
1627 0, /*tp_weaklistoffset */
1628 0, /*tp_iter */
1629 0, /*tp_iternext */
1630 0, /*tp_methods */
1631 0, /*tp_members */
1632 0, /*tp_getset */
1633 0, /*tp_base */
1634 0, /*tp_dict */
1635 0, /*tp_descr_get */
1636 0, /*tp_descr_set */
1637 0, /*tp_dictoffset */
1638 0, /*tp_init */
1639 0, /*tp_alloc */
1640 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001641};
1642
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001643PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001644 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001645 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001646};
1647
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001648/* NotImplemented is an object that can be used to signal that an
1649 operation is not implemented for the given type combination. */
1650
1651static PyObject *
1652NotImplemented_repr(PyObject *op)
1653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001655}
1656
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001657static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301658NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001659{
1660 return PyUnicode_FromString("NotImplemented");
1661}
1662
1663static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301664 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001665 {NULL, NULL}
1666};
1667
1668static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001669notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1670{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001671 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001672 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1673 return NULL;
1674 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001675 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001676}
1677
Armin Ronacher226b1db2012-10-06 14:28:58 +02001678static void
1679notimplemented_dealloc(PyObject* ignore)
1680{
1681 /* This should never get called, but we also don't want to SEGV if
1682 * we accidentally decref NotImplemented out of existence.
1683 */
1684 Py_FatalError("deallocating NotImplemented");
1685}
1686
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001687PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1689 "NotImplementedType",
1690 0,
1691 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001692 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 0, /*tp_print*/
1694 0, /*tp_getattr*/
1695 0, /*tp_setattr*/
1696 0, /*tp_reserved*/
1697 NotImplemented_repr, /*tp_repr*/
1698 0, /*tp_as_number*/
1699 0, /*tp_as_sequence*/
1700 0, /*tp_as_mapping*/
1701 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001702 0, /*tp_call */
1703 0, /*tp_str */
1704 0, /*tp_getattro */
1705 0, /*tp_setattro */
1706 0, /*tp_as_buffer */
1707 Py_TPFLAGS_DEFAULT, /*tp_flags */
1708 0, /*tp_doc */
1709 0, /*tp_traverse */
1710 0, /*tp_clear */
1711 0, /*tp_richcompare */
1712 0, /*tp_weaklistoffset */
1713 0, /*tp_iter */
1714 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001715 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001716 0, /*tp_members */
1717 0, /*tp_getset */
1718 0, /*tp_base */
1719 0, /*tp_dict */
1720 0, /*tp_descr_get */
1721 0, /*tp_descr_set */
1722 0, /*tp_dictoffset */
1723 0, /*tp_init */
1724 0, /*tp_alloc */
1725 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001726};
1727
1728PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001730 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001731};
1732
Guido van Rossumba21a492001-08-16 08:17:26 +00001733void
1734_Py_ReadyTypes(void)
1735{
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001736 if (PyType_Ready(&PyBaseObject_Type) < 0)
1737 Py_FatalError("Can't initialize object type");
1738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (PyType_Ready(&PyType_Type) < 0)
1740 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1743 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1746 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1749 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001750
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001751 if (PyType_Ready(&PyLong_Type) < 0)
1752 Py_FatalError("Can't initialize int type");
1753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (PyType_Ready(&PyBool_Type) < 0)
1755 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (PyType_Ready(&PyByteArray_Type) < 0)
1758 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (PyType_Ready(&PyBytes_Type) < 0)
1761 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (PyType_Ready(&PyList_Type) < 0)
1764 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001765
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001766 if (PyType_Ready(&_PyNone_Type) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001768
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001769 if (PyType_Ready(&_PyNotImplemented_Type) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 if (PyType_Ready(&PyTraceBack_Type) < 0)
1773 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 if (PyType_Ready(&PySuper_Type) < 0)
1776 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 if (PyType_Ready(&PyRange_Type) < 0)
1779 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (PyType_Ready(&PyDict_Type) < 0)
1782 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001783
Benjamin Petersondb87c992016-11-06 13:01:07 -08001784 if (PyType_Ready(&PyDictKeys_Type) < 0)
1785 Py_FatalError("Can't initialize dict keys type");
1786
1787 if (PyType_Ready(&PyDictValues_Type) < 0)
1788 Py_FatalError("Can't initialize dict values type");
1789
1790 if (PyType_Ready(&PyDictItems_Type) < 0)
1791 Py_FatalError("Can't initialize dict items type");
1792
Eric Snow96c6af92015-05-29 22:21:39 -06001793 if (PyType_Ready(&PyODict_Type) < 0)
1794 Py_FatalError("Can't initialize OrderedDict type");
1795
1796 if (PyType_Ready(&PyODictKeys_Type) < 0)
1797 Py_FatalError("Can't initialize odict_keys type");
1798
1799 if (PyType_Ready(&PyODictItems_Type) < 0)
1800 Py_FatalError("Can't initialize odict_items type");
1801
1802 if (PyType_Ready(&PyODictValues_Type) < 0)
1803 Py_FatalError("Can't initialize odict_values type");
1804
1805 if (PyType_Ready(&PyODictIter_Type) < 0)
1806 Py_FatalError("Can't initialize odict_keyiterator type");
1807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 if (PyType_Ready(&PySet_Type) < 0)
1809 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (PyType_Ready(&PyUnicode_Type) < 0)
1812 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (PyType_Ready(&PySlice_Type) < 0)
1815 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1818 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (PyType_Ready(&PyComplex_Type) < 0)
1821 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (PyType_Ready(&PyFloat_Type) < 0)
1824 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1827 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (PyType_Ready(&PyProperty_Type) < 0)
1830 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001831
Stefan Krah9a2d99e2012-02-25 12:24:21 +01001832 if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
1833 Py_FatalError("Can't initialize managed buffer type");
1834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 if (PyType_Ready(&PyMemoryView_Type) < 0)
1836 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 if (PyType_Ready(&PyTuple_Type) < 0)
1839 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (PyType_Ready(&PyEnum_Type) < 0)
1842 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (PyType_Ready(&PyReversed_Type) < 0)
1845 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1848 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 if (PyType_Ready(&PyCode_Type) < 0)
1851 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 if (PyType_Ready(&PyFrame_Type) < 0)
1854 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (PyType_Ready(&PyCFunction_Type) < 0)
1857 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 if (PyType_Ready(&PyMethod_Type) < 0)
1860 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (PyType_Ready(&PyFunction_Type) < 0)
1863 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (PyType_Ready(&PyDictProxy_Type) < 0)
1866 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (PyType_Ready(&PyGen_Type) < 0)
1869 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1872 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1875 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001876
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001877 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1878 Py_FatalError("Can't initialize method wrapper type");
1879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (PyType_Ready(&PyEllipsis_Type) < 0)
1881 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1884 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001885
Barry Warsaw409da152012-06-03 16:18:47 -04001886 if (PyType_Ready(&_PyNamespace_Type) < 0)
1887 Py_FatalError("Can't initialize namespace type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -04001888
Benjamin Petersonc4311282012-10-30 23:21:10 -04001889 if (PyType_Ready(&PyCapsule_Type) < 0)
1890 Py_FatalError("Can't initialize capsule type");
1891
1892 if (PyType_Ready(&PyLongRangeIter_Type) < 0)
1893 Py_FatalError("Can't initialize long range iterator type");
1894
1895 if (PyType_Ready(&PyCell_Type) < 0)
1896 Py_FatalError("Can't initialize cell type");
1897
1898 if (PyType_Ready(&PyInstanceMethod_Type) < 0)
1899 Py_FatalError("Can't initialize instance method type");
1900
1901 if (PyType_Ready(&PyClassMethodDescr_Type) < 0)
1902 Py_FatalError("Can't initialize class method descr type");
1903
1904 if (PyType_Ready(&PyMethodDescr_Type) < 0)
1905 Py_FatalError("Can't initialize method descr type");
1906
1907 if (PyType_Ready(&PyCallIter_Type) < 0)
1908 Py_FatalError("Can't initialize call iter type");
1909
1910 if (PyType_Ready(&PySeqIter_Type) < 0)
1911 Py_FatalError("Can't initialize sequence iterator type");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001912
1913 if (PyType_Ready(&PyCoro_Type) < 0)
1914 Py_FatalError("Can't initialize coroutine type");
1915
1916 if (PyType_Ready(&_PyCoroWrapper_Type) < 0)
1917 Py_FatalError("Can't initialize coroutine wrapper type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001918}
1919
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001920
Guido van Rossum84a90321996-05-22 16:34:47 +00001921#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001922
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001923void
Fred Drake100814d2000-07-09 15:48:49 +00001924_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001925{
Victor Stinner9e00e802018-10-25 13:31:16 +02001926 if (_Py_tracemalloc_config.tracing) {
1927 _PyTraceMalloc_NewReference(op);
1928 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 _Py_INC_REFTOTAL;
1930 op->ob_refcnt = 1;
1931 _Py_AddToAllObjects(op, 1);
1932 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001933}
1934
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001935void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001936_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001937{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001938#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001939 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001940#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 if (op->ob_refcnt < 0)
1942 Py_FatalError("UNREF negative refcnt");
1943 if (op == &refchain ||
1944 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1945 fprintf(stderr, "* ob\n");
1946 _PyObject_Dump(op);
1947 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1948 _PyObject_Dump(op->_ob_prev->_ob_next);
1949 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1950 _PyObject_Dump(op->_ob_next->_ob_prev);
1951 Py_FatalError("UNREF invalid object");
1952 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001953#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1955 if (p == op)
1956 break;
1957 }
1958 if (p == &refchain) /* Not found */
1959 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001960#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 op->_ob_next->_ob_prev = op->_ob_prev;
1962 op->_ob_prev->_ob_next = op->_ob_next;
1963 op->_ob_next = op->_ob_prev = NULL;
1964 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001965}
1966
Tim Peters269b2a62003-04-17 19:52:29 +00001967/* Print all live objects. Because PyObject_Print is called, the
1968 * interpreter must be in a healthy state.
1969 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001970void
Fred Drake100814d2000-07-09 15:48:49 +00001971_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 PyObject *op;
1974 fprintf(fp, "Remaining objects:\n");
1975 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1976 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1977 if (PyObject_Print(op, fp, 0) != 0)
1978 PyErr_Clear();
1979 putc('\n', fp);
1980 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001981}
1982
Tim Peters269b2a62003-04-17 19:52:29 +00001983/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1984 * doesn't make any calls to the Python C API, so is always safe to call.
1985 */
1986void
1987_Py_PrintReferenceAddresses(FILE *fp)
1988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyObject *op;
1990 fprintf(fp, "Remaining object addresses:\n");
1991 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1992 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1993 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001994}
1995
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001996PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001997_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 int i, n;
2000 PyObject *t = NULL;
2001 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2004 return NULL;
2005 op = refchain._ob_next;
2006 res = PyList_New(0);
2007 if (res == NULL)
2008 return NULL;
2009 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2010 while (op == self || op == args || op == res || op == t ||
2011 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2012 op = op->_ob_next;
2013 if (op == &refchain)
2014 return res;
2015 }
2016 if (PyList_Append(res, op) < 0) {
2017 Py_DECREF(res);
2018 return NULL;
2019 }
2020 op = op->_ob_next;
2021 }
2022 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002023}
2024
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002025#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002026
Benjamin Petersonb173f782009-05-05 22:31:58 +00002027
Guido van Rossum84a90321996-05-22 16:34:47 +00002028/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002029Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002030
2031
David Malcolm49526f42012-06-22 14:55:41 -04002032void
2033_PyObject_DebugTypeStats(FILE *out)
2034{
2035 _PyCFunction_DebugMallocStats(out);
2036 _PyDict_DebugMallocStats(out);
2037 _PyFloat_DebugMallocStats(out);
2038 _PyFrame_DebugMallocStats(out);
2039 _PyList_DebugMallocStats(out);
2040 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04002041 _PyTuple_DebugMallocStats(out);
2042}
Guido van Rossumb18618d2000-05-03 23:44:39 +00002043
Guido van Rossum86610361998-04-10 22:32:46 +00002044/* These methods are used to control infinite recursion in repr, str, print,
2045 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00002046 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00002047 Py_ReprLeave() to avoid infinite recursion.
2048
2049 Py_ReprEnter() returns 0 the first time it is called for a particular
2050 object and 1 every time thereafter. It returns -1 if an exception
2051 occurred. Py_ReprLeave() has no return value.
2052
2053 See dictobject.c and listobject.c for examples of use.
2054*/
2055
Guido van Rossum86610361998-04-10 22:32:46 +00002056int
Fred Drake100814d2000-07-09 15:48:49 +00002057Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 PyObject *dict;
2060 PyObject *list;
2061 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02002064 /* Ignore a missing thread-state, so that this function can be called
2065 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 if (dict == NULL)
2067 return 0;
Victor Stinner7a07e452013-11-06 18:57:29 +01002068 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (list == NULL) {
2070 list = PyList_New(0);
2071 if (list == NULL)
2072 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01002073 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 return -1;
2075 Py_DECREF(list);
2076 }
2077 i = PyList_GET_SIZE(list);
2078 while (--i >= 0) {
2079 if (PyList_GET_ITEM(list, i) == obj)
2080 return 1;
2081 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002082 if (PyList_Append(list, obj) < 0)
2083 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002085}
2086
2087void
Fred Drake100814d2000-07-09 15:48:49 +00002088Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 PyObject *dict;
2091 PyObject *list;
2092 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002093 PyObject *error_type, *error_value, *error_traceback;
2094
2095 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 dict = PyThreadState_GetDict();
2098 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002099 goto finally;
2100
Victor Stinner7a07e452013-11-06 18:57:29 +01002101 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002103 goto finally;
2104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 i = PyList_GET_SIZE(list);
2106 /* Count backwards because we always expect obj to be list[-1] */
2107 while (--i >= 0) {
2108 if (PyList_GET_ITEM(list, i) == obj) {
2109 PyList_SetSlice(list, i, i + 1, NULL);
2110 break;
2111 }
2112 }
Victor Stinner1b634932013-07-16 22:24:44 +02002113
2114finally:
2115 /* ignore exceptions because there is no way to report them. */
2116 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002117}
Guido van Rossumd724b232000-03-13 16:01:29 +00002118
Tim Peters803526b2002-07-07 05:13:56 +00002119/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002120
Tim Peters803526b2002-07-07 05:13:56 +00002121/* Add op to the _PyTrash_delete_later list. Called when the current
2122 * call-stack depth gets large. op must be a currently untracked gc'ed
2123 * object, with refcount 0. Py_DECREF must already have been called on it.
2124 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002125void
Fred Drake100814d2000-07-09 15:48:49 +00002126_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002127{
Victor Stinner24702042018-10-26 17:16:37 +02002128 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2129 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2130 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002131 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002132 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002133}
2134
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002135/* The equivalent API, using per-thread state recursion info */
2136void
2137_PyTrash_thread_deposit_object(PyObject *op)
2138{
Victor Stinner50b48572018-11-01 01:51:40 +01002139 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002140 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2141 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2142 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002143 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002144 tstate->trash_delete_later = op;
2145}
2146
Tim Peters803526b2002-07-07 05:13:56 +00002147/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2148 * the call-stack unwinds again.
2149 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002150void
Fred Drake100814d2000-07-09 15:48:49 +00002151_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002152{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002153 while (_PyRuntime.gc.trash_delete_later) {
2154 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002156
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002157 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002158 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* Call the deallocator directly. This used to try to
2161 * fool Py_DECREF into calling it indirectly, but
2162 * Py_DECREF was already called on this object, and in
2163 * assorted non-release builds calling Py_DECREF again ends
2164 * up distorting allocation statistics.
2165 */
Victor Stinner24702042018-10-26 17:16:37 +02002166 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002167 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002169 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002171}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002172
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002173/* The equivalent API, using per-thread state recursion info */
2174void
2175_PyTrash_thread_destroy_chain(void)
2176{
Victor Stinner50b48572018-11-01 01:51:40 +01002177 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002178 /* We need to increase trash_delete_nesting here, otherwise,
2179 _PyTrash_thread_destroy_chain will be called recursively
2180 and then possibly crash. An example that may crash without
2181 increase:
2182 N = 500000 # need to be large enough
2183 ob = object()
2184 tups = [(ob,) for i in range(N)]
2185 for i in range(49):
2186 tups = [(tup,) for tup in tups]
2187 del tups
2188 */
2189 assert(tstate->trash_delete_nesting == 0);
2190 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002191 while (tstate->trash_delete_later) {
2192 PyObject *op = tstate->trash_delete_later;
2193 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2194
2195 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002196 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002197
2198 /* Call the deallocator directly. This used to try to
2199 * fool Py_DECREF into calling it indirectly, but
2200 * Py_DECREF was already called on this object, and in
2201 * assorted non-release builds calling Py_DECREF again ends
2202 * up distorting allocation statistics.
2203 */
Victor Stinner24702042018-10-26 17:16:37 +02002204 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002205 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002206 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002207 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002208 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002209}
2210
Victor Stinner626bff82018-10-25 17:31:10 +02002211
2212void
2213_PyObject_AssertFailed(PyObject *obj, const char *msg, const char *expr,
2214 const char *file, int line, const char *function)
2215{
2216 fprintf(stderr,
2217 "%s:%d: %s: Assertion \"%s\" failed",
2218 file, line, function, expr);
2219 fflush(stderr);
2220
2221 if (msg) {
2222 fprintf(stderr, "; %s.\n", msg);
2223 }
2224 else {
2225 fprintf(stderr, ".\n");
2226 }
2227 fflush(stderr);
2228
2229 if (obj == NULL) {
2230 fprintf(stderr, "<NULL object>\n");
2231 }
2232 else if (_PyObject_IsFreed(obj)) {
2233 /* It seems like the object memory has been freed:
2234 don't access it to prevent a segmentation fault. */
2235 fprintf(stderr, "<Freed object>\n");
2236 }
2237 else {
2238 /* Diplay the traceback where the object has been allocated.
2239 Do it before dumping repr(obj), since repr() is more likely
2240 to crash than dumping the traceback. */
2241 void *ptr;
2242 PyTypeObject *type = Py_TYPE(obj);
2243 if (PyType_IS_GC(type)) {
2244 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2245 }
2246 else {
2247 ptr = (void *)obj;
2248 }
2249 _PyMem_DumpTraceback(fileno(stderr), ptr);
2250
2251 /* This might succeed or fail, but we're about to abort, so at least
2252 try to provide any extra info we can: */
2253 _PyObject_Dump(obj);
2254 }
2255 fflush(stderr);
2256
2257 Py_FatalError("_PyObject_AssertFailed");
2258}
2259
Victor Stinner3c09dca2018-10-30 14:48:26 +01002260
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002261#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002262
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002263void
2264_Py_Dealloc(PyObject *op)
2265{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002266 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2267#ifdef Py_TRACE_REFS
2268 _Py_ForgetReference(op);
2269#else
2270 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002271#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002272 (*dealloc)(op);
2273}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002274
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002275#ifdef __cplusplus
2276}
2277#endif