blob: c2d78aa47e65c562785f1571c1ea402361e42446 [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 Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pystate.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01006#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 Stinnerf1d002c2018-11-21 23:53:44 +0100208 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200209 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000210}
211
212#endif /* Py_REF_DEBUG */
213
Thomas Heller1328b522004-04-22 17:23:49 +0000214void
215Py_IncRef(PyObject *o)
216{
217 Py_XINCREF(o);
218}
219
220void
221Py_DecRef(PyObject *o)
222{
223 Py_XDECREF(o);
224}
225
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000226PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000227PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if (op == NULL)
230 return PyErr_NoMemory();
231 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
232 Py_TYPE(op) = tp;
233 _Py_NewReference(op);
234 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235}
236
Guido van Rossumb18618d2000-05-03 23:44:39 +0000237PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000238PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (op == NULL)
241 return (PyVarObject *) PyErr_NoMemory();
242 /* Any changes should be reflected in PyObject_INIT_VAR */
243 op->ob_size = size;
244 Py_TYPE(op) = tp;
245 _Py_NewReference((PyObject *)op);
246 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000247}
248
249PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000250_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 PyObject *op;
253 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
254 if (op == NULL)
255 return PyErr_NoMemory();
256 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000257}
258
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000259PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000260_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 PyVarObject *op;
263 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
264 op = (PyVarObject *) PyObject_MALLOC(size);
265 if (op == NULL)
266 return (PyVarObject *)PyErr_NoMemory();
267 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000268}
269
Antoine Pitrou796564c2013-07-30 19:59:21 +0200270void
271PyObject_CallFinalizer(PyObject *self)
272{
273 PyTypeObject *tp = Py_TYPE(self);
274
275 /* The former could happen on heaptypes created from the C API, e.g.
276 PyType_FromSpec(). */
277 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
278 tp->tp_finalize == NULL)
279 return;
280 /* tp_finalize should only be called once. */
281 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
282 return;
283
284 tp->tp_finalize(self);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900285 if (PyType_IS_GC(tp)) {
286 _PyGC_SET_FINALIZED(self);
287 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200288}
289
290int
291PyObject_CallFinalizerFromDealloc(PyObject *self)
292{
293 Py_ssize_t refcnt;
294
295 /* Temporarily resurrect the object. */
296 if (self->ob_refcnt != 0) {
297 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
298 "object with a non-zero refcount");
299 }
300 self->ob_refcnt = 1;
301
302 PyObject_CallFinalizer(self);
303
304 /* Undo the temporary resurrection; can't use DECREF here, it would
305 * cause a recursive call.
306 */
Victor Stinner24702042018-10-26 17:16:37 +0200307 _PyObject_ASSERT_WITH_MSG(self,
308 self->ob_refcnt > 0,
309 "refcount is too small");
Antoine Pitrou796564c2013-07-30 19:59:21 +0200310 if (--self->ob_refcnt == 0)
311 return 0; /* this is the normal path out */
312
313 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
314 * never happened.
315 */
316 refcnt = self->ob_refcnt;
317 _Py_NewReference(self);
318 self->ob_refcnt = refcnt;
319
Victor Stinner24702042018-10-26 17:16:37 +0200320 _PyObject_ASSERT(self,
321 (!PyType_IS_GC(Py_TYPE(self))
322 || _PyObject_GC_IS_TRACKED(self)));
Antoine Pitrou796564c2013-07-30 19:59:21 +0200323 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
324 * we need to undo that. */
325 _Py_DEC_REFTOTAL;
326 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
327 * chain, so no more to do there.
328 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
329 * _Py_NewReference bumped tp_allocs: both of those need to be
330 * undone.
331 */
332#ifdef COUNT_ALLOCS
333 --Py_TYPE(self)->tp_frees;
334 --Py_TYPE(self)->tp_allocs;
335#endif
336 return -1;
337}
338
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000339int
340PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (PyErr_CheckSignals())
344 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000345#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (PyOS_CheckStack()) {
347 PyErr_SetString(PyExc_MemoryError, "stack overflow");
348 return -1;
349 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000350#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 clearerr(fp); /* Clear any previous error condition */
352 if (op == NULL) {
353 Py_BEGIN_ALLOW_THREADS
354 fprintf(fp, "<nil>");
355 Py_END_ALLOW_THREADS
356 }
357 else {
Victor Stinner3ec9af72018-10-26 02:12:34 +0200358 if (op->ob_refcnt <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 /* XXX(twouters) cast refcount to long until %zd is
360 universally available */
361 Py_BEGIN_ALLOW_THREADS
362 fprintf(fp, "<refcnt %ld at %p>",
363 (long)op->ob_refcnt, op);
364 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200365 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 else {
367 PyObject *s;
368 if (flags & Py_PRINT_RAW)
369 s = PyObject_Str(op);
370 else
371 s = PyObject_Repr(op);
372 if (s == NULL)
373 ret = -1;
374 else if (PyBytes_Check(s)) {
375 fwrite(PyBytes_AS_STRING(s), 1,
376 PyBytes_GET_SIZE(s), fp);
377 }
378 else if (PyUnicode_Check(s)) {
379 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200380 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600381 if (t == NULL) {
382 ret = -1;
383 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 else {
385 fwrite(PyBytes_AS_STRING(t), 1,
386 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000387 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 }
389 }
390 else {
391 PyErr_Format(PyExc_TypeError,
392 "str() or repr() returned '%.100s'",
393 s->ob_type->tp_name);
394 ret = -1;
395 }
396 Py_XDECREF(s);
397 }
398 }
399 if (ret == 0) {
400 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300401 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 clearerr(fp);
403 ret = -1;
404 }
405 }
406 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407}
408
Guido van Rossum38938152006-08-21 23:36:26 +0000409/* For debugging convenience. Set a breakpoint here and call it from your DLL */
410void
Thomas Woutersb2137042007-02-01 18:02:27 +0000411_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000412{
413}
414
Neal Norwitz1a997502003-01-13 20:13:12 +0000415
Victor Stinner82af0b62018-10-23 17:39:40 +0200416/* Heuristic checking if the object memory has been deallocated.
417 Rely on the debug hooks on Python memory allocators which fills the memory
418 with DEADBYTE (0xDB) when memory is deallocated.
419
420 The function can be used to prevent segmentation fault on dereferencing
421 pointers like 0xdbdbdbdbdbdbdbdb. Such pointer is very unlikely to be mapped
422 in memory. */
423int
424_PyObject_IsFreed(PyObject *op)
425{
Victor Stinner2cf5d322018-11-22 16:32:57 +0100426 uintptr_t ptr = (uintptr_t)op;
427 if (_PyMem_IsFreed(&ptr, sizeof(ptr))) {
428 return 1;
429 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200430 int freed = _PyMem_IsFreed(&op->ob_type, sizeof(op->ob_type));
431 /* ignore op->ob_ref: the value can have be modified
432 by Py_INCREF() and Py_DECREF(). */
433#ifdef Py_TRACE_REFS
434 freed &= _PyMem_IsFreed(&op->_ob_next, sizeof(op->_ob_next));
435 freed &= _PyMem_IsFreed(&op->_ob_prev, sizeof(op->_ob_prev));
436#endif
437 return freed;
438}
439
440
Barry Warsaw9bf16442001-01-23 16:24:35 +0000441/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000442void
443_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000444{
Victor Stinner82af0b62018-10-23 17:39:40 +0200445 if (op == NULL) {
446 fprintf(stderr, "<NULL object>\n");
447 fflush(stderr);
448 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200450
451 if (_PyObject_IsFreed(op)) {
452 /* It seems like the object memory has been freed:
453 don't access it to prevent a segmentation fault. */
454 fprintf(stderr, "<freed object>\n");
Victor Stinner2cf5d322018-11-22 16:32:57 +0100455 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200456 }
457
458 PyGILState_STATE gil;
459 PyObject *error_type, *error_value, *error_traceback;
460
461 fprintf(stderr, "object : ");
462 fflush(stderr);
463 gil = PyGILState_Ensure();
464
465 PyErr_Fetch(&error_type, &error_value, &error_traceback);
466 (void)PyObject_Print(op, stderr, 0);
467 fflush(stderr);
468 PyErr_Restore(error_type, error_value, error_traceback);
469
470 PyGILState_Release(gil);
471 /* XXX(twouters) cast refcount to long until %zd is
472 universally available */
473 fprintf(stderr, "\n"
474 "type : %s\n"
475 "refcount: %ld\n"
476 "address : %p\n",
477 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
478 (long)op->ob_refcnt,
479 op);
480 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000481}
Barry Warsaw903138f2001-01-23 16:33:18 +0000482
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000484PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyObject *res;
487 if (PyErr_CheckSignals())
488 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000489#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (PyOS_CheckStack()) {
491 PyErr_SetString(PyExc_MemoryError, "stack overflow");
492 return NULL;
493 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000494#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (v == NULL)
496 return PyUnicode_FromString("<NULL>");
497 if (Py_TYPE(v)->tp_repr == NULL)
498 return PyUnicode_FromFormat("<%s object at %p>",
499 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200500
501#ifdef Py_DEBUG
502 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100503 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000504 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200505 assert(!PyErr_Occurred());
506#endif
507
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200508 /* It is possible for a type to have a tp_repr representation that loops
509 infinitely. */
510 if (Py_EnterRecursiveCall(" while getting the repr of an object"))
511 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 res = (*v->ob_type->tp_repr)(v);
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200513 Py_LeaveRecursiveCall();
Victor Stinner0a54cf12011-12-01 03:22:44 +0100514 if (res == NULL)
515 return NULL;
516 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyErr_Format(PyExc_TypeError,
518 "__repr__ returned non-string (type %.200s)",
519 res->ob_type->tp_name);
520 Py_DECREF(res);
521 return NULL;
522 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100523#ifndef Py_DEBUG
524 if (PyUnicode_READY(res) < 0)
525 return NULL;
526#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528}
529
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000531PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyObject *res;
534 if (PyErr_CheckSignals())
535 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000536#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (PyOS_CheckStack()) {
538 PyErr_SetString(PyExc_MemoryError, "stack overflow");
539 return NULL;
540 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000541#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (v == NULL)
543 return PyUnicode_FromString("<NULL>");
544 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100545#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100546 if (PyUnicode_READY(v) < 0)
547 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100548#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 Py_INCREF(v);
550 return v;
551 }
552 if (Py_TYPE(v)->tp_str == NULL)
553 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000554
Victor Stinner33824f62013-08-26 14:05:19 +0200555#ifdef Py_DEBUG
556 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100557 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000558 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200559 assert(!PyErr_Occurred());
560#endif
561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* It is possible for a type to have a tp_str representation that loops
563 infinitely. */
564 if (Py_EnterRecursiveCall(" while getting the str of an object"))
565 return NULL;
566 res = (*Py_TYPE(v)->tp_str)(v);
567 Py_LeaveRecursiveCall();
568 if (res == NULL)
569 return NULL;
570 if (!PyUnicode_Check(res)) {
571 PyErr_Format(PyExc_TypeError,
572 "__str__ returned non-string (type %.200s)",
573 Py_TYPE(res)->tp_name);
574 Py_DECREF(res);
575 return NULL;
576 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100577#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100578 if (PyUnicode_READY(res) < 0)
579 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100580#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100581 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000583}
584
Georg Brandl559e5d72008-06-11 18:37:52 +0000585PyObject *
586PyObject_ASCII(PyObject *v)
587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 repr = PyObject_Repr(v);
591 if (repr == NULL)
592 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000593
Victor Stinneraf037572013-04-14 18:44:10 +0200594 if (PyUnicode_IS_ASCII(repr))
595 return repr;
596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200598 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 Py_DECREF(repr);
600 if (ascii == NULL)
601 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 res = PyUnicode_DecodeASCII(
604 PyBytes_AS_STRING(ascii),
605 PyBytes_GET_SIZE(ascii),
606 NULL);
607
608 Py_DECREF(ascii);
609 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000610}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000611
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000612PyObject *
613PyObject_Bytes(PyObject *v)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (v == NULL)
618 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (PyBytes_CheckExact(v)) {
621 Py_INCREF(v);
622 return v;
623 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000624
Benjamin Petersonce798522012-01-22 11:24:29 -0500625 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100627 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 Py_DECREF(func);
629 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000630 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000632 PyErr_Format(PyExc_TypeError,
633 "__bytes__ returned non-bytes (type %.200s)",
634 Py_TYPE(result)->tp_name);
635 Py_DECREF(result);
636 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 }
638 return result;
639 }
640 else if (PyErr_Occurred())
641 return NULL;
642 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000643}
644
Mark Dickinsonc008a172009-02-01 13:59:22 +0000645/* For Python 3.0.1 and later, the old three-way comparison has been
646 completely removed in favour of rich comparisons. PyObject_Compare() and
647 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000648 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000649 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000650
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000651 See (*) below for practical amendments.
652
Mark Dickinsonc008a172009-02-01 13:59:22 +0000653 tp_richcompare gets called with a first argument of the appropriate type
654 and a second object of an arbitrary type. We never do any kind of
655 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000656
Mark Dickinsonc008a172009-02-01 13:59:22 +0000657 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000658
659 NULL if an exception occurred
660 NotImplemented if the requested comparison is not implemented
661 any other false value if the requested comparison is false
662 any other true value if the requested comparison is true
663
664 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
665 NotImplemented.
666
667 (*) Practical amendments:
668
669 - If rich comparison returns NotImplemented, == and != are decided by
670 comparing the object pointer (i.e. falling back to the base object
671 implementation).
672
Guido van Rossuma4073002002-05-31 20:03:54 +0000673*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000674
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000675/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000676int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000677
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200678static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000679
680/* Perform a rich comparison, raising TypeError when the requested comparison
681 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000682static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000683do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 richcmpfunc f;
686 PyObject *res;
687 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (v->ob_type != w->ob_type &&
690 PyType_IsSubtype(w->ob_type, v->ob_type) &&
691 (f = w->ob_type->tp_richcompare) != NULL) {
692 checked_reverse_op = 1;
693 res = (*f)(w, v, _Py_SwappedOp[op]);
694 if (res != Py_NotImplemented)
695 return res;
696 Py_DECREF(res);
697 }
698 if ((f = v->ob_type->tp_richcompare) != NULL) {
699 res = (*f)(v, w, op);
700 if (res != Py_NotImplemented)
701 return res;
702 Py_DECREF(res);
703 }
704 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
705 res = (*f)(w, v, _Py_SwappedOp[op]);
706 if (res != Py_NotImplemented)
707 return res;
708 Py_DECREF(res);
709 }
710 /* If neither object implements it, provide a sensible default
711 for == and !=, but raise an exception for ordering. */
712 switch (op) {
713 case Py_EQ:
714 res = (v == w) ? Py_True : Py_False;
715 break;
716 case Py_NE:
717 res = (v != w) ? Py_True : Py_False;
718 break;
719 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 PyErr_Format(PyExc_TypeError,
Victor Stinner91108f02015-10-14 18:25:31 +0200721 "'%s' not supported between instances of '%.100s' and '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 opstrings[op],
Victor Stinner91108f02015-10-14 18:25:31 +0200723 v->ob_type->tp_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 w->ob_type->tp_name);
725 return NULL;
726 }
727 Py_INCREF(res);
728 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000729}
730
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000731/* Perform a rich comparison with object result. This wraps do_richcompare()
732 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000733
Guido van Rossume797ec12001-01-17 15:24:28 +0000734PyObject *
735PyObject_RichCompare(PyObject *v, PyObject *w, int op)
736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 assert(Py_LT <= op && op <= Py_GE);
740 if (v == NULL || w == NULL) {
741 if (!PyErr_Occurred())
742 PyErr_BadInternalCall();
743 return NULL;
744 }
745 if (Py_EnterRecursiveCall(" in comparison"))
746 return NULL;
747 res = do_richcompare(v, w, op);
748 Py_LeaveRecursiveCall();
749 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000750}
751
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000752/* Perform a rich comparison with integer result. This wraps
753 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000754int
755PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 PyObject *res;
758 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 /* Quick result when objects are the same.
761 Guarantees that identity implies equality. */
762 if (v == w) {
763 if (op == Py_EQ)
764 return 1;
765 else if (op == Py_NE)
766 return 0;
767 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 res = PyObject_RichCompare(v, w, op);
770 if (res == NULL)
771 return -1;
772 if (PyBool_Check(res))
773 ok = (res == Py_True);
774 else
775 ok = PyObject_IsTrue(res);
776 Py_DECREF(res);
777 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000778}
Fred Drake13634cf2000-06-29 19:17:04 +0000779
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100780Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000781PyObject_HashNotImplemented(PyObject *v)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
784 Py_TYPE(v)->tp_name);
785 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000786}
Fred Drake13634cf2000-06-29 19:17:04 +0000787
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000788Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000789PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 PyTypeObject *tp = Py_TYPE(v);
792 if (tp->tp_hash != NULL)
793 return (*tp->tp_hash)(v);
794 /* To keep to the general practice that inheriting
795 * solely from object in C code should work without
796 * an explicit call to PyType_Ready, we implicitly call
797 * PyType_Ready here and then check the tp_hash slot again
798 */
799 if (tp->tp_dict == NULL) {
800 if (PyType_Ready(tp) < 0)
801 return -1;
802 if (tp->tp_hash != NULL)
803 return (*tp->tp_hash)(v);
804 }
805 /* Otherwise, the object can't be hashed */
806 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000807}
808
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000809PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000810PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (Py_TYPE(v)->tp_getattr != NULL)
815 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900816 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (w == NULL)
818 return NULL;
819 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100820 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000822}
823
824int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000825PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyObject *res = PyObject_GetAttrString(v, name);
828 if (res != NULL) {
829 Py_DECREF(res);
830 return 1;
831 }
832 PyErr_Clear();
833 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000834}
835
836int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000837PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyObject *s;
840 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 if (Py_TYPE(v)->tp_setattr != NULL)
843 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
844 s = PyUnicode_InternFromString(name);
845 if (s == NULL)
846 return -1;
847 res = PyObject_SetAttr(v, s, w);
848 Py_XDECREF(s);
849 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000850}
851
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500852int
853_PyObject_IsAbstract(PyObject *obj)
854{
855 int res;
856 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500857
858 if (obj == NULL)
859 return 0;
860
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200861 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
862 if (res > 0) {
863 res = PyObject_IsTrue(isabstract);
864 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500865 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500866 return res;
867}
868
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000869PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200870_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
871{
872 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100873 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200874 if (!oname)
875 return NULL;
876 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200877 return result;
878}
879
880int
881_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
882{
883 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100884 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200885 if (!oname)
886 return -1;
887 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200888 return result;
889}
890
891int
892_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
893{
894 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100895 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200896 if (!oname)
897 return -1;
898 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200899 return result;
900}
901
902PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000903PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 if (!PyUnicode_Check(name)) {
908 PyErr_Format(PyExc_TypeError,
909 "attribute name must be string, not '%.200s'",
910 name->ob_type->tp_name);
911 return NULL;
912 }
913 if (tp->tp_getattro != NULL)
914 return (*tp->tp_getattro)(v, name);
915 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200916 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 if (name_str == NULL)
918 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200919 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 }
921 PyErr_Format(PyExc_AttributeError,
922 "'%.50s' object has no attribute '%U'",
923 tp->tp_name, name);
924 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000925}
926
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200927int
928_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900929{
930 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900931
932 if (!PyUnicode_Check(name)) {
933 PyErr_Format(PyExc_TypeError,
934 "attribute name must be string, not '%.200s'",
935 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200936 *result = NULL;
937 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900938 }
939
940 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200941 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
942 if (*result != NULL) {
943 return 1;
944 }
945 if (PyErr_Occurred()) {
946 return -1;
947 }
948 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900949 }
950 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200951 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900952 }
953 else if (tp->tp_getattr != NULL) {
954 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200955 if (name_str == NULL) {
956 *result = NULL;
957 return -1;
958 }
959 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900960 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900961 else {
962 *result = NULL;
963 return 0;
964 }
965
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200966 if (*result != NULL) {
967 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900968 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200969 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
970 return -1;
971 }
972 PyErr_Clear();
973 return 0;
974}
975
976int
977_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
978{
979 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
980 if (!oname) {
981 *result = NULL;
982 return -1;
983 }
984 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +0900985}
986
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000987int
Fred Drake100814d2000-07-09 15:48:49 +0000988PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000989{
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200990 PyObject *res;
991 if (_PyObject_LookupAttr(v, name, &res) < 0) {
992 PyErr_Clear();
993 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200995 if (res == NULL) {
996 return 0;
997 }
998 Py_DECREF(res);
999 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001000}
1001
1002int
Fred Drake100814d2000-07-09 15:48:49 +00001003PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyTypeObject *tp = Py_TYPE(v);
1006 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (!PyUnicode_Check(name)) {
1009 PyErr_Format(PyExc_TypeError,
1010 "attribute name must be string, not '%.200s'",
1011 name->ob_type->tp_name);
1012 return -1;
1013 }
1014 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PyUnicode_InternInPlace(&name);
1017 if (tp->tp_setattro != NULL) {
1018 err = (*tp->tp_setattro)(v, name, value);
1019 Py_DECREF(name);
1020 return err;
1021 }
1022 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001023 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (name_str == NULL)
1025 return -1;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001026 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 Py_DECREF(name);
1028 return err;
1029 }
1030 Py_DECREF(name);
Victor Stinner24702042018-10-26 17:16:37 +02001031 _PyObject_ASSERT(name, name->ob_refcnt >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1033 PyErr_Format(PyExc_TypeError,
1034 "'%.100s' object has no attributes "
1035 "(%s .%U)",
1036 tp->tp_name,
1037 value==NULL ? "del" : "assign to",
1038 name);
1039 else
1040 PyErr_Format(PyExc_TypeError,
1041 "'%.100s' object has only read-only attributes "
1042 "(%s .%U)",
1043 tp->tp_name,
1044 value==NULL ? "del" : "assign to",
1045 name);
1046 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047}
1048
1049/* Helper to get a pointer to an object's __dict__ slot, if any */
1050
1051PyObject **
1052_PyObject_GetDictPtr(PyObject *obj)
1053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 Py_ssize_t dictoffset;
1055 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 dictoffset = tp->tp_dictoffset;
1058 if (dictoffset == 0)
1059 return NULL;
1060 if (dictoffset < 0) {
1061 Py_ssize_t tsize;
1062 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 tsize = ((PyVarObject *)obj)->ob_size;
1065 if (tsize < 0)
1066 tsize = -tsize;
1067 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001070 _PyObject_ASSERT(obj, dictoffset > 0);
1071 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 }
1073 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074}
1075
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001077PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 Py_INCREF(obj);
1080 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001081}
1082
Antoine Pitroua7013882012-04-05 00:04:20 +02001083/* Convenience function to get a builtin from its name */
1084PyObject *
1085_PyObject_GetBuiltin(const char *name)
1086{
Victor Stinner53e9ec42013-11-07 00:43:05 +01001087 PyObject *mod_name, *mod, *attr;
1088
Victor Stinnerbd303c12013-11-07 23:07:29 +01001089 mod_name = _PyUnicode_FromId(&PyId_builtins); /* borrowed */
Victor Stinner53e9ec42013-11-07 00:43:05 +01001090 if (mod_name == NULL)
1091 return NULL;
1092 mod = PyImport_Import(mod_name);
Antoine Pitroua7013882012-04-05 00:04:20 +02001093 if (mod == NULL)
1094 return NULL;
1095 attr = PyObject_GetAttrString(mod, name);
1096 Py_DECREF(mod);
1097 return attr;
1098}
1099
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001100/* Helper used when the __next__ method is removed from a type:
1101 tp_iternext is never NULL and can be safely called without checking
1102 on every iteration.
1103 */
1104
1105PyObject *
1106_PyObject_NextNotImplemented(PyObject *self)
1107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 PyErr_Format(PyExc_TypeError,
1109 "'%.200s' object is not iterable",
1110 Py_TYPE(self)->tp_name);
1111 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001112}
1113
Yury Selivanovf2392132016-12-13 19:03:51 -05001114
1115/* Specialized version of _PyObject_GenericGetAttrWithDict
1116 specifically for the LOAD_METHOD opcode.
1117
1118 Return 1 if a method is found, 0 if it's a regular attribute
1119 from __dict__ or something returned by using a descriptor
1120 protocol.
1121
1122 `method` will point to the resolved attribute or NULL. In the
1123 latter case, an error will be set.
1124*/
1125int
1126_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1127{
1128 PyTypeObject *tp = Py_TYPE(obj);
1129 PyObject *descr;
1130 descrgetfunc f = NULL;
1131 PyObject **dictptr, *dict;
1132 PyObject *attr;
1133 int meth_found = 0;
1134
1135 assert(*method == NULL);
1136
1137 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1138 || !PyUnicode_Check(name)) {
1139 *method = PyObject_GetAttr(obj, name);
1140 return 0;
1141 }
1142
1143 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1144 return 0;
1145
1146 descr = _PyType_Lookup(tp, name);
1147 if (descr != NULL) {
1148 Py_INCREF(descr);
INADA Naoki5566bbb2017-02-03 07:43:03 +09001149 if (PyFunction_Check(descr) ||
1150 (Py_TYPE(descr) == &PyMethodDescr_Type)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001151 meth_found = 1;
1152 } else {
1153 f = descr->ob_type->tp_descr_get;
1154 if (f != NULL && PyDescr_IsData(descr)) {
1155 *method = f(descr, obj, (PyObject *)obj->ob_type);
1156 Py_DECREF(descr);
1157 return 0;
1158 }
1159 }
1160 }
1161
1162 dictptr = _PyObject_GetDictPtr(obj);
1163 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1164 Py_INCREF(dict);
1165 attr = PyDict_GetItem(dict, name);
1166 if (attr != NULL) {
1167 Py_INCREF(attr);
1168 *method = attr;
1169 Py_DECREF(dict);
1170 Py_XDECREF(descr);
1171 return 0;
1172 }
1173 Py_DECREF(dict);
1174 }
1175
1176 if (meth_found) {
1177 *method = descr;
1178 return 1;
1179 }
1180
1181 if (f != NULL) {
1182 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1183 Py_DECREF(descr);
1184 return 0;
1185 }
1186
1187 if (descr != NULL) {
1188 *method = descr;
1189 return 0;
1190 }
1191
1192 PyErr_Format(PyExc_AttributeError,
1193 "'%.50s' object has no attribute '%U'",
1194 tp->tp_name, name);
1195 return 0;
1196}
1197
1198/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001199
Raymond Hettinger01538262003-03-17 08:24:35 +00001200PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001201_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1202 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001203{
Yury Selivanovf2392132016-12-13 19:03:51 -05001204 /* Make sure the logic of _PyObject_GetMethod is in sync with
1205 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001206
1207 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001208 */
1209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyTypeObject *tp = Py_TYPE(obj);
1211 PyObject *descr = NULL;
1212 PyObject *res = NULL;
1213 descrgetfunc f;
1214 Py_ssize_t dictoffset;
1215 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (!PyUnicode_Check(name)){
1218 PyErr_Format(PyExc_TypeError,
1219 "attribute name must be string, not '%.200s'",
1220 name->ob_type->tp_name);
1221 return NULL;
1222 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001223 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (tp->tp_dict == NULL) {
1226 if (PyType_Ready(tp) < 0)
1227 goto done;
1228 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 f = NULL;
1233 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001234 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 f = descr->ob_type->tp_descr_get;
1236 if (f != NULL && PyDescr_IsData(descr)) {
1237 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001238 if (res == NULL && suppress &&
1239 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1240 PyErr_Clear();
1241 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 goto done;
1243 }
1244 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001246 if (dict == NULL) {
1247 /* Inline _PyObject_GetDictPtr */
1248 dictoffset = tp->tp_dictoffset;
1249 if (dictoffset != 0) {
1250 if (dictoffset < 0) {
1251 Py_ssize_t tsize;
1252 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001253
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001254 tsize = ((PyVarObject *)obj)->ob_size;
1255 if (tsize < 0)
1256 tsize = -tsize;
1257 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001258 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001259
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001260 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001261 _PyObject_ASSERT(obj, dictoffset > 0);
1262 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001264 dictptr = (PyObject **) ((char *)obj + dictoffset);
1265 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 }
1267 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001268 if (dict != NULL) {
1269 Py_INCREF(dict);
1270 res = PyDict_GetItem(dict, name);
1271 if (res != NULL) {
1272 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001273 Py_DECREF(dict);
1274 goto done;
1275 }
1276 Py_DECREF(dict);
1277 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (f != NULL) {
1280 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001281 if (res == NULL && suppress &&
1282 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1283 PyErr_Clear();
1284 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 goto done;
1286 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (descr != NULL) {
1289 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001290 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 goto done;
1292 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293
INADA Naoki378edee2018-01-16 20:52:41 +09001294 if (!suppress) {
1295 PyErr_Format(PyExc_AttributeError,
1296 "'%.50s' object has no attribute '%U'",
1297 tp->tp_name, name);
1298 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001299 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001300 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 Py_DECREF(name);
1302 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303}
1304
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001305PyObject *
1306PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1307{
INADA Naoki378edee2018-01-16 20:52:41 +09001308 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001309}
1310
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001312_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1313 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 PyTypeObject *tp = Py_TYPE(obj);
1316 PyObject *descr;
1317 descrsetfunc f;
1318 PyObject **dictptr;
1319 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (!PyUnicode_Check(name)){
1322 PyErr_Format(PyExc_TypeError,
1323 "attribute name must be string, not '%.200s'",
1324 name->ob_type->tp_name);
1325 return -1;
1326 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001328 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1329 return -1;
1330
1331 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001336 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001338 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 res = f(descr, obj, value);
1340 goto done;
1341 }
1342 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001343
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001344 if (dict == NULL) {
1345 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001346 if (dictptr == NULL) {
1347 if (descr == NULL) {
1348 PyErr_Format(PyExc_AttributeError,
1349 "'%.100s' object has no attribute '%U'",
1350 tp->tp_name, name);
1351 }
1352 else {
1353 PyErr_Format(PyExc_AttributeError,
1354 "'%.50s' object attribute '%U' is read-only",
1355 tp->tp_name, name);
1356 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001357 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001359 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001360 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001361 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001362 Py_INCREF(dict);
1363 if (value == NULL)
1364 res = PyDict_DelItem(dict, name);
1365 else
1366 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001367 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001369 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1370 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001371
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001372 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001373 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 Py_DECREF(name);
1375 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001376}
1377
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001378int
1379PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1380{
1381 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1382}
1383
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001384int
1385PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1386{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001387 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001388 if (dictptr == NULL) {
1389 PyErr_SetString(PyExc_AttributeError,
1390 "This object has no __dict__");
1391 return -1;
1392 }
1393 if (value == NULL) {
1394 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1395 return -1;
1396 }
1397 if (!PyDict_Check(value)) {
1398 PyErr_Format(PyExc_TypeError,
1399 "__dict__ must be set to a dictionary, "
1400 "not a '%.200s'", Py_TYPE(value)->tp_name);
1401 return -1;
1402 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001403 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001404 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001405 return 0;
1406}
1407
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001408
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001409/* Test a value used as condition, e.g., in a for or if statement.
1410 Return -1 if an error occurred */
1411
1412int
Fred Drake100814d2000-07-09 15:48:49 +00001413PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 Py_ssize_t res;
1416 if (v == Py_True)
1417 return 1;
1418 if (v == Py_False)
1419 return 0;
1420 if (v == Py_None)
1421 return 0;
1422 else if (v->ob_type->tp_as_number != NULL &&
1423 v->ob_type->tp_as_number->nb_bool != NULL)
1424 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1425 else if (v->ob_type->tp_as_mapping != NULL &&
1426 v->ob_type->tp_as_mapping->mp_length != NULL)
1427 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1428 else if (v->ob_type->tp_as_sequence != NULL &&
1429 v->ob_type->tp_as_sequence->sq_length != NULL)
1430 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1431 else
1432 return 1;
1433 /* if it is negative, it should be either -1 or -2 */
1434 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001435}
1436
Tim Peters803526b2002-07-07 05:13:56 +00001437/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001438 Return -1 if an error occurred */
1439
1440int
Fred Drake100814d2000-07-09 15:48:49 +00001441PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 int res;
1444 res = PyObject_IsTrue(v);
1445 if (res < 0)
1446 return res;
1447 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001448}
1449
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001450/* Test whether an object can be called */
1451
1452int
Fred Drake100814d2000-07-09 15:48:49 +00001453PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (x == NULL)
1456 return 0;
1457 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001458}
1459
Tim Peters7eea37e2001-09-04 22:08:56 +00001460
Georg Brandle32b4222007-03-10 22:13:27 +00001461/* Helper for PyObject_Dir without arguments: returns the local scope. */
1462static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001463_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001466 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001467
Victor Stinner41bb43a2013-10-29 01:19:37 +01001468 locals = PyEval_GetLocals();
1469 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 names = PyMapping_Keys(locals);
1473 if (!names)
1474 return NULL;
1475 if (!PyList_Check(names)) {
1476 PyErr_Format(PyExc_TypeError,
1477 "dir(): expected keys() of locals to be a list, "
1478 "not '%.200s'", Py_TYPE(names)->tp_name);
1479 Py_DECREF(names);
1480 return NULL;
1481 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001482 if (PyList_Sort(names)) {
1483 Py_DECREF(names);
1484 return NULL;
1485 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 /* the locals don't need to be DECREF'd */
1487 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001488}
1489
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001490/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001491static PyObject *
1492_dir_object(PyObject *obj)
1493{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001494 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001495 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001496
Victor Stinner24702042018-10-26 17:16:37 +02001497 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001499 if (!PyErr_Occurred())
1500 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1501 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001503 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001504 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001505 Py_DECREF(dirfunc);
1506 if (result == NULL)
1507 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001508 /* return sorted(result) */
1509 sorted = PySequence_List(result);
1510 Py_DECREF(result);
1511 if (sorted == NULL)
1512 return NULL;
1513 if (PyList_Sort(sorted)) {
1514 Py_DECREF(sorted);
1515 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001517 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001518}
1519
1520/* Implementation of dir() -- if obj is NULL, returns the names in the current
1521 (local) scope. Otherwise, performs introspection of the object: returns a
1522 sorted list of attribute names (supposedly) accessible from the object
1523*/
1524PyObject *
1525PyObject_Dir(PyObject *obj)
1526{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001527 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001528}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001529
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001530/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001531None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001532There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001533so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001534*/
1535
Guido van Rossum0c182a11992-03-27 17:26:13 +00001536/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001537static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001538none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001541}
1542
Barry Warsaw9bf16442001-01-23 16:24:35 +00001543/* ARGUSED */
1544static void
Tim Peters803526b2002-07-07 05:13:56 +00001545none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 /* This should never get called, but we also don't want to SEGV if
1548 * we accidentally decref None out of existence.
1549 */
1550 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001551}
1552
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001553static PyObject *
1554none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1555{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001556 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001557 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1558 return NULL;
1559 }
1560 Py_RETURN_NONE;
1561}
1562
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001563static int
1564none_bool(PyObject *v)
1565{
1566 return 0;
1567}
1568
1569static PyNumberMethods none_as_number = {
1570 0, /* nb_add */
1571 0, /* nb_subtract */
1572 0, /* nb_multiply */
1573 0, /* nb_remainder */
1574 0, /* nb_divmod */
1575 0, /* nb_power */
1576 0, /* nb_negative */
1577 0, /* nb_positive */
1578 0, /* nb_absolute */
1579 (inquiry)none_bool, /* nb_bool */
1580 0, /* nb_invert */
1581 0, /* nb_lshift */
1582 0, /* nb_rshift */
1583 0, /* nb_and */
1584 0, /* nb_xor */
1585 0, /* nb_or */
1586 0, /* nb_int */
1587 0, /* nb_reserved */
1588 0, /* nb_float */
1589 0, /* nb_inplace_add */
1590 0, /* nb_inplace_subtract */
1591 0, /* nb_inplace_multiply */
1592 0, /* nb_inplace_remainder */
1593 0, /* nb_inplace_power */
1594 0, /* nb_inplace_lshift */
1595 0, /* nb_inplace_rshift */
1596 0, /* nb_inplace_and */
1597 0, /* nb_inplace_xor */
1598 0, /* nb_inplace_or */
1599 0, /* nb_floor_divide */
1600 0, /* nb_true_divide */
1601 0, /* nb_inplace_floor_divide */
1602 0, /* nb_inplace_true_divide */
1603 0, /* nb_index */
1604};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001605
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001606PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1608 "NoneType",
1609 0,
1610 0,
1611 none_dealloc, /*tp_dealloc*/ /*never called*/
1612 0, /*tp_print*/
1613 0, /*tp_getattr*/
1614 0, /*tp_setattr*/
1615 0, /*tp_reserved*/
1616 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001617 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 0, /*tp_as_sequence*/
1619 0, /*tp_as_mapping*/
1620 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001621 0, /*tp_call */
1622 0, /*tp_str */
1623 0, /*tp_getattro */
1624 0, /*tp_setattro */
1625 0, /*tp_as_buffer */
1626 Py_TPFLAGS_DEFAULT, /*tp_flags */
1627 0, /*tp_doc */
1628 0, /*tp_traverse */
1629 0, /*tp_clear */
1630 0, /*tp_richcompare */
1631 0, /*tp_weaklistoffset */
1632 0, /*tp_iter */
1633 0, /*tp_iternext */
1634 0, /*tp_methods */
1635 0, /*tp_members */
1636 0, /*tp_getset */
1637 0, /*tp_base */
1638 0, /*tp_dict */
1639 0, /*tp_descr_get */
1640 0, /*tp_descr_set */
1641 0, /*tp_dictoffset */
1642 0, /*tp_init */
1643 0, /*tp_alloc */
1644 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001645};
1646
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001647PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001648 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001649 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001650};
1651
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001652/* NotImplemented is an object that can be used to signal that an
1653 operation is not implemented for the given type combination. */
1654
1655static PyObject *
1656NotImplemented_repr(PyObject *op)
1657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001659}
1660
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001661static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301662NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001663{
1664 return PyUnicode_FromString("NotImplemented");
1665}
1666
1667static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301668 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001669 {NULL, NULL}
1670};
1671
1672static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001673notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1674{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001675 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001676 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1677 return NULL;
1678 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001679 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001680}
1681
Armin Ronacher226b1db2012-10-06 14:28:58 +02001682static void
1683notimplemented_dealloc(PyObject* ignore)
1684{
1685 /* This should never get called, but we also don't want to SEGV if
1686 * we accidentally decref NotImplemented out of existence.
1687 */
1688 Py_FatalError("deallocating NotImplemented");
1689}
1690
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001691PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1693 "NotImplementedType",
1694 0,
1695 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001696 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 0, /*tp_print*/
1698 0, /*tp_getattr*/
1699 0, /*tp_setattr*/
1700 0, /*tp_reserved*/
1701 NotImplemented_repr, /*tp_repr*/
1702 0, /*tp_as_number*/
1703 0, /*tp_as_sequence*/
1704 0, /*tp_as_mapping*/
1705 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001706 0, /*tp_call */
1707 0, /*tp_str */
1708 0, /*tp_getattro */
1709 0, /*tp_setattro */
1710 0, /*tp_as_buffer */
1711 Py_TPFLAGS_DEFAULT, /*tp_flags */
1712 0, /*tp_doc */
1713 0, /*tp_traverse */
1714 0, /*tp_clear */
1715 0, /*tp_richcompare */
1716 0, /*tp_weaklistoffset */
1717 0, /*tp_iter */
1718 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001719 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001720 0, /*tp_members */
1721 0, /*tp_getset */
1722 0, /*tp_base */
1723 0, /*tp_dict */
1724 0, /*tp_descr_get */
1725 0, /*tp_descr_set */
1726 0, /*tp_dictoffset */
1727 0, /*tp_init */
1728 0, /*tp_alloc */
1729 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001730};
1731
1732PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001734 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001735};
1736
Guido van Rossumba21a492001-08-16 08:17:26 +00001737void
1738_Py_ReadyTypes(void)
1739{
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001740 if (PyType_Ready(&PyBaseObject_Type) < 0)
1741 Py_FatalError("Can't initialize object type");
1742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (PyType_Ready(&PyType_Type) < 0)
1744 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1747 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1750 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1753 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001754
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001755 if (PyType_Ready(&PyLong_Type) < 0)
1756 Py_FatalError("Can't initialize int type");
1757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (PyType_Ready(&PyBool_Type) < 0)
1759 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (PyType_Ready(&PyByteArray_Type) < 0)
1762 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 if (PyType_Ready(&PyBytes_Type) < 0)
1765 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (PyType_Ready(&PyList_Type) < 0)
1768 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001769
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001770 if (PyType_Ready(&_PyNone_Type) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001772
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001773 if (PyType_Ready(&_PyNotImplemented_Type) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (PyType_Ready(&PyTraceBack_Type) < 0)
1777 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 if (PyType_Ready(&PySuper_Type) < 0)
1780 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (PyType_Ready(&PyRange_Type) < 0)
1783 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 if (PyType_Ready(&PyDict_Type) < 0)
1786 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001787
Benjamin Petersondb87c992016-11-06 13:01:07 -08001788 if (PyType_Ready(&PyDictKeys_Type) < 0)
1789 Py_FatalError("Can't initialize dict keys type");
1790
1791 if (PyType_Ready(&PyDictValues_Type) < 0)
1792 Py_FatalError("Can't initialize dict values type");
1793
1794 if (PyType_Ready(&PyDictItems_Type) < 0)
1795 Py_FatalError("Can't initialize dict items type");
1796
Rémi Lapeyre6531bf62018-11-06 01:38:54 +01001797 if (PyType_Ready(&PyDictRevIterKey_Type) < 0)
1798 Py_FatalError("Can't initialize reversed dict keys type");
1799
1800 if (PyType_Ready(&PyDictRevIterValue_Type) < 0)
1801 Py_FatalError("Can't initialize reversed dict values type");
1802
1803 if (PyType_Ready(&PyDictRevIterItem_Type) < 0)
1804 Py_FatalError("Can't initialize reversed dict items type");
1805
Eric Snow96c6af92015-05-29 22:21:39 -06001806 if (PyType_Ready(&PyODict_Type) < 0)
1807 Py_FatalError("Can't initialize OrderedDict type");
1808
1809 if (PyType_Ready(&PyODictKeys_Type) < 0)
1810 Py_FatalError("Can't initialize odict_keys type");
1811
1812 if (PyType_Ready(&PyODictItems_Type) < 0)
1813 Py_FatalError("Can't initialize odict_items type");
1814
1815 if (PyType_Ready(&PyODictValues_Type) < 0)
1816 Py_FatalError("Can't initialize odict_values type");
1817
1818 if (PyType_Ready(&PyODictIter_Type) < 0)
1819 Py_FatalError("Can't initialize odict_keyiterator type");
1820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (PyType_Ready(&PySet_Type) < 0)
1822 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 if (PyType_Ready(&PyUnicode_Type) < 0)
1825 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 if (PyType_Ready(&PySlice_Type) < 0)
1828 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1831 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (PyType_Ready(&PyComplex_Type) < 0)
1834 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 if (PyType_Ready(&PyFloat_Type) < 0)
1837 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1840 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 if (PyType_Ready(&PyProperty_Type) < 0)
1843 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001844
Stefan Krah9a2d99e2012-02-25 12:24:21 +01001845 if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
1846 Py_FatalError("Can't initialize managed buffer type");
1847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 if (PyType_Ready(&PyMemoryView_Type) < 0)
1849 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 if (PyType_Ready(&PyTuple_Type) < 0)
1852 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 if (PyType_Ready(&PyEnum_Type) < 0)
1855 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if (PyType_Ready(&PyReversed_Type) < 0)
1858 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1861 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 if (PyType_Ready(&PyCode_Type) < 0)
1864 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (PyType_Ready(&PyFrame_Type) < 0)
1867 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 if (PyType_Ready(&PyCFunction_Type) < 0)
1870 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (PyType_Ready(&PyMethod_Type) < 0)
1873 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (PyType_Ready(&PyFunction_Type) < 0)
1876 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (PyType_Ready(&PyDictProxy_Type) < 0)
1879 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (PyType_Ready(&PyGen_Type) < 0)
1882 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1885 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1888 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001889
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001890 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1891 Py_FatalError("Can't initialize method wrapper type");
1892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (PyType_Ready(&PyEllipsis_Type) < 0)
1894 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1897 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001898
Barry Warsaw409da152012-06-03 16:18:47 -04001899 if (PyType_Ready(&_PyNamespace_Type) < 0)
1900 Py_FatalError("Can't initialize namespace type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -04001901
Benjamin Petersonc4311282012-10-30 23:21:10 -04001902 if (PyType_Ready(&PyCapsule_Type) < 0)
1903 Py_FatalError("Can't initialize capsule type");
1904
1905 if (PyType_Ready(&PyLongRangeIter_Type) < 0)
1906 Py_FatalError("Can't initialize long range iterator type");
1907
1908 if (PyType_Ready(&PyCell_Type) < 0)
1909 Py_FatalError("Can't initialize cell type");
1910
1911 if (PyType_Ready(&PyInstanceMethod_Type) < 0)
1912 Py_FatalError("Can't initialize instance method type");
1913
1914 if (PyType_Ready(&PyClassMethodDescr_Type) < 0)
1915 Py_FatalError("Can't initialize class method descr type");
1916
1917 if (PyType_Ready(&PyMethodDescr_Type) < 0)
1918 Py_FatalError("Can't initialize method descr type");
1919
1920 if (PyType_Ready(&PyCallIter_Type) < 0)
1921 Py_FatalError("Can't initialize call iter type");
1922
1923 if (PyType_Ready(&PySeqIter_Type) < 0)
1924 Py_FatalError("Can't initialize sequence iterator type");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001925
1926 if (PyType_Ready(&PyCoro_Type) < 0)
1927 Py_FatalError("Can't initialize coroutine type");
1928
1929 if (PyType_Ready(&_PyCoroWrapper_Type) < 0)
1930 Py_FatalError("Can't initialize coroutine wrapper type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001931}
1932
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001933
Guido van Rossum84a90321996-05-22 16:34:47 +00001934#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001935
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001936void
Fred Drake100814d2000-07-09 15:48:49 +00001937_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001938{
Victor Stinner9e00e802018-10-25 13:31:16 +02001939 if (_Py_tracemalloc_config.tracing) {
1940 _PyTraceMalloc_NewReference(op);
1941 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 _Py_INC_REFTOTAL;
1943 op->ob_refcnt = 1;
1944 _Py_AddToAllObjects(op, 1);
1945 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001946}
1947
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001948void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001949_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001950{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001951#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001952 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001953#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (op->ob_refcnt < 0)
1955 Py_FatalError("UNREF negative refcnt");
1956 if (op == &refchain ||
1957 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1958 fprintf(stderr, "* ob\n");
1959 _PyObject_Dump(op);
1960 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1961 _PyObject_Dump(op->_ob_prev->_ob_next);
1962 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1963 _PyObject_Dump(op->_ob_next->_ob_prev);
1964 Py_FatalError("UNREF invalid object");
1965 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001966#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1968 if (p == op)
1969 break;
1970 }
1971 if (p == &refchain) /* Not found */
1972 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001973#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 op->_ob_next->_ob_prev = op->_ob_prev;
1975 op->_ob_prev->_ob_next = op->_ob_next;
1976 op->_ob_next = op->_ob_prev = NULL;
1977 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001978}
1979
Tim Peters269b2a62003-04-17 19:52:29 +00001980/* Print all live objects. Because PyObject_Print is called, the
1981 * interpreter must be in a healthy state.
1982 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001983void
Fred Drake100814d2000-07-09 15:48:49 +00001984_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 PyObject *op;
1987 fprintf(fp, "Remaining objects:\n");
1988 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1989 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1990 if (PyObject_Print(op, fp, 0) != 0)
1991 PyErr_Clear();
1992 putc('\n', fp);
1993 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001994}
1995
Tim Peters269b2a62003-04-17 19:52:29 +00001996/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1997 * doesn't make any calls to the Python C API, so is always safe to call.
1998 */
1999void
2000_Py_PrintReferenceAddresses(FILE *fp)
2001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyObject *op;
2003 fprintf(fp, "Remaining object addresses:\n");
2004 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
2005 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
2006 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00002007}
2008
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002009PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002010_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 int i, n;
2013 PyObject *t = NULL;
2014 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2017 return NULL;
2018 op = refchain._ob_next;
2019 res = PyList_New(0);
2020 if (res == NULL)
2021 return NULL;
2022 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2023 while (op == self || op == args || op == res || op == t ||
2024 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2025 op = op->_ob_next;
2026 if (op == &refchain)
2027 return res;
2028 }
2029 if (PyList_Append(res, op) < 0) {
2030 Py_DECREF(res);
2031 return NULL;
2032 }
2033 op = op->_ob_next;
2034 }
2035 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002036}
2037
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002038#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002039
Benjamin Petersonb173f782009-05-05 22:31:58 +00002040
Guido van Rossum84a90321996-05-22 16:34:47 +00002041/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002042Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002043
2044
David Malcolm49526f42012-06-22 14:55:41 -04002045void
2046_PyObject_DebugTypeStats(FILE *out)
2047{
2048 _PyCFunction_DebugMallocStats(out);
2049 _PyDict_DebugMallocStats(out);
2050 _PyFloat_DebugMallocStats(out);
2051 _PyFrame_DebugMallocStats(out);
2052 _PyList_DebugMallocStats(out);
2053 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04002054 _PyTuple_DebugMallocStats(out);
2055}
Guido van Rossumb18618d2000-05-03 23:44:39 +00002056
Guido van Rossum86610361998-04-10 22:32:46 +00002057/* These methods are used to control infinite recursion in repr, str, print,
2058 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00002059 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00002060 Py_ReprLeave() to avoid infinite recursion.
2061
2062 Py_ReprEnter() returns 0 the first time it is called for a particular
2063 object and 1 every time thereafter. It returns -1 if an exception
2064 occurred. Py_ReprLeave() has no return value.
2065
2066 See dictobject.c and listobject.c for examples of use.
2067*/
2068
Guido van Rossum86610361998-04-10 22:32:46 +00002069int
Fred Drake100814d2000-07-09 15:48:49 +00002070Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 PyObject *dict;
2073 PyObject *list;
2074 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02002077 /* Ignore a missing thread-state, so that this function can be called
2078 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 if (dict == NULL)
2080 return 0;
Victor Stinner7a07e452013-11-06 18:57:29 +01002081 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 if (list == NULL) {
2083 list = PyList_New(0);
2084 if (list == NULL)
2085 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01002086 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 return -1;
2088 Py_DECREF(list);
2089 }
2090 i = PyList_GET_SIZE(list);
2091 while (--i >= 0) {
2092 if (PyList_GET_ITEM(list, i) == obj)
2093 return 1;
2094 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002095 if (PyList_Append(list, obj) < 0)
2096 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002098}
2099
2100void
Fred Drake100814d2000-07-09 15:48:49 +00002101Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *dict;
2104 PyObject *list;
2105 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002106 PyObject *error_type, *error_value, *error_traceback;
2107
2108 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 dict = PyThreadState_GetDict();
2111 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002112 goto finally;
2113
Victor Stinner7a07e452013-11-06 18:57:29 +01002114 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002116 goto finally;
2117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 i = PyList_GET_SIZE(list);
2119 /* Count backwards because we always expect obj to be list[-1] */
2120 while (--i >= 0) {
2121 if (PyList_GET_ITEM(list, i) == obj) {
2122 PyList_SetSlice(list, i, i + 1, NULL);
2123 break;
2124 }
2125 }
Victor Stinner1b634932013-07-16 22:24:44 +02002126
2127finally:
2128 /* ignore exceptions because there is no way to report them. */
2129 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002130}
Guido van Rossumd724b232000-03-13 16:01:29 +00002131
Tim Peters803526b2002-07-07 05:13:56 +00002132/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002133
Tim Peters803526b2002-07-07 05:13:56 +00002134/* Add op to the _PyTrash_delete_later list. Called when the current
2135 * call-stack depth gets large. op must be a currently untracked gc'ed
2136 * object, with refcount 0. Py_DECREF must already have been called on it.
2137 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002138void
Fred Drake100814d2000-07-09 15:48:49 +00002139_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002140{
Victor Stinner24702042018-10-26 17:16:37 +02002141 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2142 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2143 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002144 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002145 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002146}
2147
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002148/* The equivalent API, using per-thread state recursion info */
2149void
2150_PyTrash_thread_deposit_object(PyObject *op)
2151{
Victor Stinner50b48572018-11-01 01:51:40 +01002152 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002153 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2154 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2155 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002156 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002157 tstate->trash_delete_later = op;
2158}
2159
Tim Peters803526b2002-07-07 05:13:56 +00002160/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2161 * the call-stack unwinds again.
2162 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002163void
Fred Drake100814d2000-07-09 15:48:49 +00002164_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002165{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002166 while (_PyRuntime.gc.trash_delete_later) {
2167 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002169
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002170 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002171 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 /* Call the deallocator directly. This used to try to
2174 * fool Py_DECREF into calling it indirectly, but
2175 * Py_DECREF was already called on this object, and in
2176 * assorted non-release builds calling Py_DECREF again ends
2177 * up distorting allocation statistics.
2178 */
Victor Stinner24702042018-10-26 17:16:37 +02002179 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002180 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002182 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002184}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002185
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002186/* The equivalent API, using per-thread state recursion info */
2187void
2188_PyTrash_thread_destroy_chain(void)
2189{
Victor Stinner50b48572018-11-01 01:51:40 +01002190 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002191 /* We need to increase trash_delete_nesting here, otherwise,
2192 _PyTrash_thread_destroy_chain will be called recursively
2193 and then possibly crash. An example that may crash without
2194 increase:
2195 N = 500000 # need to be large enough
2196 ob = object()
2197 tups = [(ob,) for i in range(N)]
2198 for i in range(49):
2199 tups = [(tup,) for tup in tups]
2200 del tups
2201 */
2202 assert(tstate->trash_delete_nesting == 0);
2203 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002204 while (tstate->trash_delete_later) {
2205 PyObject *op = tstate->trash_delete_later;
2206 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2207
2208 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002209 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002210
2211 /* Call the deallocator directly. This used to try to
2212 * fool Py_DECREF into calling it indirectly, but
2213 * Py_DECREF was already called on this object, and in
2214 * assorted non-release builds calling Py_DECREF again ends
2215 * up distorting allocation statistics.
2216 */
Victor Stinner24702042018-10-26 17:16:37 +02002217 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002218 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002219 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002220 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002221 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002222}
2223
Victor Stinner626bff82018-10-25 17:31:10 +02002224
2225void
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002226_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002227 const char *file, int line, const char *function)
2228{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002229 fprintf(stderr, "%s:%d: ", file, line);
2230 if (function) {
2231 fprintf(stderr, "%s: ", function);
2232 }
Victor Stinner626bff82018-10-25 17:31:10 +02002233 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002234 if (expr) {
2235 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002236 }
2237 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002238 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002239 }
2240 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002241 if (msg) {
2242 fprintf(stderr, ": %s", msg);
2243 }
2244 fprintf(stderr, "\n");
2245 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002246
2247 if (obj == NULL) {
2248 fprintf(stderr, "<NULL object>\n");
2249 }
2250 else if (_PyObject_IsFreed(obj)) {
2251 /* It seems like the object memory has been freed:
2252 don't access it to prevent a segmentation fault. */
2253 fprintf(stderr, "<Freed object>\n");
2254 }
2255 else {
2256 /* Diplay the traceback where the object has been allocated.
2257 Do it before dumping repr(obj), since repr() is more likely
2258 to crash than dumping the traceback. */
2259 void *ptr;
2260 PyTypeObject *type = Py_TYPE(obj);
2261 if (PyType_IS_GC(type)) {
2262 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2263 }
2264 else {
2265 ptr = (void *)obj;
2266 }
2267 _PyMem_DumpTraceback(fileno(stderr), ptr);
2268
2269 /* This might succeed or fail, but we're about to abort, so at least
2270 try to provide any extra info we can: */
2271 _PyObject_Dump(obj);
2272 }
2273 fflush(stderr);
2274
2275 Py_FatalError("_PyObject_AssertFailed");
2276}
2277
Victor Stinner3c09dca2018-10-30 14:48:26 +01002278
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002279#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002280
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002281void
2282_Py_Dealloc(PyObject *op)
2283{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002284 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2285#ifdef Py_TRACE_REFS
2286 _Py_ForgetReference(op);
2287#else
2288 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002289#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002290 (*dealloc)(op);
2291}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002292
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002293#ifdef __cplusplus
2294}
2295#endif