blob: b446d598130a25b3aaab7378237887964f8b38de [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"
Eric Snowc11183c2019-03-15 16:35:46 -06008#include "interpreteridobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010#ifdef __cplusplus
11extern "C" {
12#endif
13
Victor Stinner626bff82018-10-25 17:31:10 +020014/* Defined in tracemalloc.c */
15extern void _PyMem_DumpTraceback(int fd, const void *ptr);
16
Victor Stinnerbd303c12013-11-07 23:07:29 +010017_Py_IDENTIFIER(Py_Repr);
18_Py_IDENTIFIER(__bytes__);
19_Py_IDENTIFIER(__dir__);
20_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010021
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
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001083/* Helper used when the __next__ method is removed from a type:
1084 tp_iternext is never NULL and can be safely called without checking
1085 on every iteration.
1086 */
1087
1088PyObject *
1089_PyObject_NextNotImplemented(PyObject *self)
1090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyErr_Format(PyExc_TypeError,
1092 "'%.200s' object is not iterable",
1093 Py_TYPE(self)->tp_name);
1094 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001095}
1096
Yury Selivanovf2392132016-12-13 19:03:51 -05001097
1098/* Specialized version of _PyObject_GenericGetAttrWithDict
1099 specifically for the LOAD_METHOD opcode.
1100
1101 Return 1 if a method is found, 0 if it's a regular attribute
1102 from __dict__ or something returned by using a descriptor
1103 protocol.
1104
1105 `method` will point to the resolved attribute or NULL. In the
1106 latter case, an error will be set.
1107*/
1108int
1109_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1110{
1111 PyTypeObject *tp = Py_TYPE(obj);
1112 PyObject *descr;
1113 descrgetfunc f = NULL;
1114 PyObject **dictptr, *dict;
1115 PyObject *attr;
1116 int meth_found = 0;
1117
1118 assert(*method == NULL);
1119
1120 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1121 || !PyUnicode_Check(name)) {
1122 *method = PyObject_GetAttr(obj, name);
1123 return 0;
1124 }
1125
1126 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1127 return 0;
1128
1129 descr = _PyType_Lookup(tp, name);
1130 if (descr != NULL) {
1131 Py_INCREF(descr);
INADA Naoki5566bbb2017-02-03 07:43:03 +09001132 if (PyFunction_Check(descr) ||
1133 (Py_TYPE(descr) == &PyMethodDescr_Type)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001134 meth_found = 1;
1135 } else {
1136 f = descr->ob_type->tp_descr_get;
1137 if (f != NULL && PyDescr_IsData(descr)) {
1138 *method = f(descr, obj, (PyObject *)obj->ob_type);
1139 Py_DECREF(descr);
1140 return 0;
1141 }
1142 }
1143 }
1144
1145 dictptr = _PyObject_GetDictPtr(obj);
1146 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1147 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001148 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001149 if (attr != NULL) {
1150 Py_INCREF(attr);
1151 *method = attr;
1152 Py_DECREF(dict);
1153 Py_XDECREF(descr);
1154 return 0;
1155 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001156 else {
1157 Py_DECREF(dict);
1158 if (PyErr_Occurred()) {
1159 Py_XDECREF(descr);
1160 return 0;
1161 }
1162 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001163 }
1164
1165 if (meth_found) {
1166 *method = descr;
1167 return 1;
1168 }
1169
1170 if (f != NULL) {
1171 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1172 Py_DECREF(descr);
1173 return 0;
1174 }
1175
1176 if (descr != NULL) {
1177 *method = descr;
1178 return 0;
1179 }
1180
1181 PyErr_Format(PyExc_AttributeError,
1182 "'%.50s' object has no attribute '%U'",
1183 tp->tp_name, name);
1184 return 0;
1185}
1186
1187/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001188
Raymond Hettinger01538262003-03-17 08:24:35 +00001189PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001190_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1191 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192{
Yury Selivanovf2392132016-12-13 19:03:51 -05001193 /* Make sure the logic of _PyObject_GetMethod is in sync with
1194 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001195
1196 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001197 */
1198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyTypeObject *tp = Py_TYPE(obj);
1200 PyObject *descr = NULL;
1201 PyObject *res = NULL;
1202 descrgetfunc f;
1203 Py_ssize_t dictoffset;
1204 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (!PyUnicode_Check(name)){
1207 PyErr_Format(PyExc_TypeError,
1208 "attribute name must be string, not '%.200s'",
1209 name->ob_type->tp_name);
1210 return NULL;
1211 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001212 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 if (tp->tp_dict == NULL) {
1215 if (PyType_Ready(tp) < 0)
1216 goto done;
1217 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 f = NULL;
1222 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001223 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 f = descr->ob_type->tp_descr_get;
1225 if (f != NULL && PyDescr_IsData(descr)) {
1226 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001227 if (res == NULL && suppress &&
1228 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1229 PyErr_Clear();
1230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 goto done;
1232 }
1233 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001234
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001235 if (dict == NULL) {
1236 /* Inline _PyObject_GetDictPtr */
1237 dictoffset = tp->tp_dictoffset;
1238 if (dictoffset != 0) {
1239 if (dictoffset < 0) {
1240 Py_ssize_t tsize;
1241 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001242
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001243 tsize = ((PyVarObject *)obj)->ob_size;
1244 if (tsize < 0)
1245 tsize = -tsize;
1246 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001247 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001248
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001249 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001250 _PyObject_ASSERT(obj, dictoffset > 0);
1251 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001253 dictptr = (PyObject **) ((char *)obj + dictoffset);
1254 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 }
1256 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001257 if (dict != NULL) {
1258 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001259 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001260 if (res != NULL) {
1261 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001262 Py_DECREF(dict);
1263 goto done;
1264 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001265 else {
1266 Py_DECREF(dict);
1267 if (PyErr_Occurred()) {
1268 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1269 PyErr_Clear();
1270 }
1271 else {
1272 goto done;
1273 }
1274 }
1275 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001276 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (f != NULL) {
1279 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001280 if (res == NULL && suppress &&
1281 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1282 PyErr_Clear();
1283 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 goto done;
1285 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (descr != NULL) {
1288 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001289 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 goto done;
1291 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001292
INADA Naoki378edee2018-01-16 20:52:41 +09001293 if (!suppress) {
1294 PyErr_Format(PyExc_AttributeError,
1295 "'%.50s' object has no attribute '%U'",
1296 tp->tp_name, name);
1297 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001298 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001299 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 Py_DECREF(name);
1301 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001302}
1303
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001304PyObject *
1305PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1306{
INADA Naoki378edee2018-01-16 20:52:41 +09001307 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001308}
1309
Tim Peters6d6c1a32001-08-02 04:15:00 +00001310int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001311_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1312 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 PyTypeObject *tp = Py_TYPE(obj);
1315 PyObject *descr;
1316 descrsetfunc f;
1317 PyObject **dictptr;
1318 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (!PyUnicode_Check(name)){
1321 PyErr_Format(PyExc_TypeError,
1322 "attribute name must be string, not '%.200s'",
1323 name->ob_type->tp_name);
1324 return -1;
1325 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001326
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001327 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1328 return -1;
1329
1330 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001335 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001337 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 res = f(descr, obj, value);
1339 goto done;
1340 }
1341 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001342
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001343 if (dict == NULL) {
1344 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001345 if (dictptr == NULL) {
1346 if (descr == NULL) {
1347 PyErr_Format(PyExc_AttributeError,
1348 "'%.100s' object has no attribute '%U'",
1349 tp->tp_name, name);
1350 }
1351 else {
1352 PyErr_Format(PyExc_AttributeError,
1353 "'%.50s' object attribute '%U' is read-only",
1354 tp->tp_name, name);
1355 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001356 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001358 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001359 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001360 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001361 Py_INCREF(dict);
1362 if (value == NULL)
1363 res = PyDict_DelItem(dict, name);
1364 else
1365 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001366 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001368 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1369 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001371 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001372 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 Py_DECREF(name);
1374 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001375}
1376
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001377int
1378PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1379{
1380 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1381}
1382
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001383int
1384PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1385{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001386 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001387 if (dictptr == NULL) {
1388 PyErr_SetString(PyExc_AttributeError,
1389 "This object has no __dict__");
1390 return -1;
1391 }
1392 if (value == NULL) {
1393 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1394 return -1;
1395 }
1396 if (!PyDict_Check(value)) {
1397 PyErr_Format(PyExc_TypeError,
1398 "__dict__ must be set to a dictionary, "
1399 "not a '%.200s'", Py_TYPE(value)->tp_name);
1400 return -1;
1401 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001402 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001403 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001404 return 0;
1405}
1406
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001407
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001408/* Test a value used as condition, e.g., in a for or if statement.
1409 Return -1 if an error occurred */
1410
1411int
Fred Drake100814d2000-07-09 15:48:49 +00001412PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 Py_ssize_t res;
1415 if (v == Py_True)
1416 return 1;
1417 if (v == Py_False)
1418 return 0;
1419 if (v == Py_None)
1420 return 0;
1421 else if (v->ob_type->tp_as_number != NULL &&
1422 v->ob_type->tp_as_number->nb_bool != NULL)
1423 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1424 else if (v->ob_type->tp_as_mapping != NULL &&
1425 v->ob_type->tp_as_mapping->mp_length != NULL)
1426 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1427 else if (v->ob_type->tp_as_sequence != NULL &&
1428 v->ob_type->tp_as_sequence->sq_length != NULL)
1429 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1430 else
1431 return 1;
1432 /* if it is negative, it should be either -1 or -2 */
1433 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001434}
1435
Tim Peters803526b2002-07-07 05:13:56 +00001436/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001437 Return -1 if an error occurred */
1438
1439int
Fred Drake100814d2000-07-09 15:48:49 +00001440PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 int res;
1443 res = PyObject_IsTrue(v);
1444 if (res < 0)
1445 return res;
1446 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001447}
1448
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001449/* Test whether an object can be called */
1450
1451int
Fred Drake100814d2000-07-09 15:48:49 +00001452PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (x == NULL)
1455 return 0;
1456 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001457}
1458
Tim Peters7eea37e2001-09-04 22:08:56 +00001459
Georg Brandle32b4222007-03-10 22:13:27 +00001460/* Helper for PyObject_Dir without arguments: returns the local scope. */
1461static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001462_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001465 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001466
Victor Stinner41bb43a2013-10-29 01:19:37 +01001467 locals = PyEval_GetLocals();
1468 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 names = PyMapping_Keys(locals);
1472 if (!names)
1473 return NULL;
1474 if (!PyList_Check(names)) {
1475 PyErr_Format(PyExc_TypeError,
1476 "dir(): expected keys() of locals to be a list, "
1477 "not '%.200s'", Py_TYPE(names)->tp_name);
1478 Py_DECREF(names);
1479 return NULL;
1480 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001481 if (PyList_Sort(names)) {
1482 Py_DECREF(names);
1483 return NULL;
1484 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 /* the locals don't need to be DECREF'd */
1486 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001487}
1488
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001489/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001490static PyObject *
1491_dir_object(PyObject *obj)
1492{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001493 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001494 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001495
Victor Stinner24702042018-10-26 17:16:37 +02001496 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001498 if (!PyErr_Occurred())
1499 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1500 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001502 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001503 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001504 Py_DECREF(dirfunc);
1505 if (result == NULL)
1506 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001507 /* return sorted(result) */
1508 sorted = PySequence_List(result);
1509 Py_DECREF(result);
1510 if (sorted == NULL)
1511 return NULL;
1512 if (PyList_Sort(sorted)) {
1513 Py_DECREF(sorted);
1514 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001516 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001517}
1518
1519/* Implementation of dir() -- if obj is NULL, returns the names in the current
1520 (local) scope. Otherwise, performs introspection of the object: returns a
1521 sorted list of attribute names (supposedly) accessible from the object
1522*/
1523PyObject *
1524PyObject_Dir(PyObject *obj)
1525{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001526 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001527}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001528
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001529/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001530None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001531There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001532so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001533*/
1534
Guido van Rossum0c182a11992-03-27 17:26:13 +00001535/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001536static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001537none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001540}
1541
Barry Warsaw9bf16442001-01-23 16:24:35 +00001542/* ARGUSED */
1543static void
Tim Peters803526b2002-07-07 05:13:56 +00001544none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 /* This should never get called, but we also don't want to SEGV if
1547 * we accidentally decref None out of existence.
1548 */
1549 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001550}
1551
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001552static PyObject *
1553none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1554{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001555 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001556 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1557 return NULL;
1558 }
1559 Py_RETURN_NONE;
1560}
1561
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001562static int
1563none_bool(PyObject *v)
1564{
1565 return 0;
1566}
1567
1568static PyNumberMethods none_as_number = {
1569 0, /* nb_add */
1570 0, /* nb_subtract */
1571 0, /* nb_multiply */
1572 0, /* nb_remainder */
1573 0, /* nb_divmod */
1574 0, /* nb_power */
1575 0, /* nb_negative */
1576 0, /* nb_positive */
1577 0, /* nb_absolute */
1578 (inquiry)none_bool, /* nb_bool */
1579 0, /* nb_invert */
1580 0, /* nb_lshift */
1581 0, /* nb_rshift */
1582 0, /* nb_and */
1583 0, /* nb_xor */
1584 0, /* nb_or */
1585 0, /* nb_int */
1586 0, /* nb_reserved */
1587 0, /* nb_float */
1588 0, /* nb_inplace_add */
1589 0, /* nb_inplace_subtract */
1590 0, /* nb_inplace_multiply */
1591 0, /* nb_inplace_remainder */
1592 0, /* nb_inplace_power */
1593 0, /* nb_inplace_lshift */
1594 0, /* nb_inplace_rshift */
1595 0, /* nb_inplace_and */
1596 0, /* nb_inplace_xor */
1597 0, /* nb_inplace_or */
1598 0, /* nb_floor_divide */
1599 0, /* nb_true_divide */
1600 0, /* nb_inplace_floor_divide */
1601 0, /* nb_inplace_true_divide */
1602 0, /* nb_index */
1603};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001604
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001605PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1607 "NoneType",
1608 0,
1609 0,
1610 none_dealloc, /*tp_dealloc*/ /*never called*/
1611 0, /*tp_print*/
1612 0, /*tp_getattr*/
1613 0, /*tp_setattr*/
1614 0, /*tp_reserved*/
1615 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001616 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 0, /*tp_as_sequence*/
1618 0, /*tp_as_mapping*/
1619 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001620 0, /*tp_call */
1621 0, /*tp_str */
1622 0, /*tp_getattro */
1623 0, /*tp_setattro */
1624 0, /*tp_as_buffer */
1625 Py_TPFLAGS_DEFAULT, /*tp_flags */
1626 0, /*tp_doc */
1627 0, /*tp_traverse */
1628 0, /*tp_clear */
1629 0, /*tp_richcompare */
1630 0, /*tp_weaklistoffset */
1631 0, /*tp_iter */
1632 0, /*tp_iternext */
1633 0, /*tp_methods */
1634 0, /*tp_members */
1635 0, /*tp_getset */
1636 0, /*tp_base */
1637 0, /*tp_dict */
1638 0, /*tp_descr_get */
1639 0, /*tp_descr_set */
1640 0, /*tp_dictoffset */
1641 0, /*tp_init */
1642 0, /*tp_alloc */
1643 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001644};
1645
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001646PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001647 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001648 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001649};
1650
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001651/* NotImplemented is an object that can be used to signal that an
1652 operation is not implemented for the given type combination. */
1653
1654static PyObject *
1655NotImplemented_repr(PyObject *op)
1656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001658}
1659
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001660static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301661NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001662{
1663 return PyUnicode_FromString("NotImplemented");
1664}
1665
1666static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301667 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001668 {NULL, NULL}
1669};
1670
1671static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001672notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1673{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001674 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001675 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1676 return NULL;
1677 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001678 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001679}
1680
Armin Ronacher226b1db2012-10-06 14:28:58 +02001681static void
1682notimplemented_dealloc(PyObject* ignore)
1683{
1684 /* This should never get called, but we also don't want to SEGV if
1685 * we accidentally decref NotImplemented out of existence.
1686 */
1687 Py_FatalError("deallocating NotImplemented");
1688}
1689
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001690PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1692 "NotImplementedType",
1693 0,
1694 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001695 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 0, /*tp_print*/
1697 0, /*tp_getattr*/
1698 0, /*tp_setattr*/
1699 0, /*tp_reserved*/
1700 NotImplemented_repr, /*tp_repr*/
1701 0, /*tp_as_number*/
1702 0, /*tp_as_sequence*/
1703 0, /*tp_as_mapping*/
1704 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001705 0, /*tp_call */
1706 0, /*tp_str */
1707 0, /*tp_getattro */
1708 0, /*tp_setattro */
1709 0, /*tp_as_buffer */
1710 Py_TPFLAGS_DEFAULT, /*tp_flags */
1711 0, /*tp_doc */
1712 0, /*tp_traverse */
1713 0, /*tp_clear */
1714 0, /*tp_richcompare */
1715 0, /*tp_weaklistoffset */
1716 0, /*tp_iter */
1717 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001718 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001719 0, /*tp_members */
1720 0, /*tp_getset */
1721 0, /*tp_base */
1722 0, /*tp_dict */
1723 0, /*tp_descr_get */
1724 0, /*tp_descr_set */
1725 0, /*tp_dictoffset */
1726 0, /*tp_init */
1727 0, /*tp_alloc */
1728 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001729};
1730
1731PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001733 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001734};
1735
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001736_PyInitError
Victor Stinnerab672812019-01-23 15:04:40 +01001737_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001738{
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001739#define INIT_TYPE(TYPE, NAME) \
1740 do { \
1741 if (PyType_Ready(TYPE) < 0) { \
1742 return _Py_INIT_ERR("Can't initialize " NAME " type"); \
1743 } \
1744 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001745
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001746 INIT_TYPE(&PyBaseObject_Type, "object");
1747 INIT_TYPE(&PyType_Type, "type");
1748 INIT_TYPE(&_PyWeakref_RefType, "weakref");
1749 INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
1750 INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
1751 INIT_TYPE(&PyLong_Type, "int");
1752 INIT_TYPE(&PyBool_Type, "bool");
1753 INIT_TYPE(&PyByteArray_Type, "bytearray");
1754 INIT_TYPE(&PyBytes_Type, "str");
1755 INIT_TYPE(&PyList_Type, "list");
1756 INIT_TYPE(&_PyNone_Type, "None");
1757 INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
1758 INIT_TYPE(&PyTraceBack_Type, "traceback");
1759 INIT_TYPE(&PySuper_Type, "super");
1760 INIT_TYPE(&PyRange_Type, "range");
1761 INIT_TYPE(&PyDict_Type, "dict");
1762 INIT_TYPE(&PyDictKeys_Type, "dict keys");
1763 INIT_TYPE(&PyDictValues_Type, "dict values");
1764 INIT_TYPE(&PyDictItems_Type, "dict items");
1765 INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
1766 INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
1767 INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
1768 INIT_TYPE(&PyODict_Type, "OrderedDict");
1769 INIT_TYPE(&PyODictKeys_Type, "odict_keys");
1770 INIT_TYPE(&PyODictItems_Type, "odict_items");
1771 INIT_TYPE(&PyODictValues_Type, "odict_values");
1772 INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
1773 INIT_TYPE(&PySet_Type, "set");
1774 INIT_TYPE(&PyUnicode_Type, "str");
1775 INIT_TYPE(&PySlice_Type, "slice");
1776 INIT_TYPE(&PyStaticMethod_Type, "static method");
1777 INIT_TYPE(&PyComplex_Type, "complex");
1778 INIT_TYPE(&PyFloat_Type, "float");
1779 INIT_TYPE(&PyFrozenSet_Type, "frozenset");
1780 INIT_TYPE(&PyProperty_Type, "property");
1781 INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
1782 INIT_TYPE(&PyMemoryView_Type, "memoryview");
1783 INIT_TYPE(&PyTuple_Type, "tuple");
1784 INIT_TYPE(&PyEnum_Type, "enumerate");
1785 INIT_TYPE(&PyReversed_Type, "reversed");
1786 INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
1787 INIT_TYPE(&PyCode_Type, "code");
1788 INIT_TYPE(&PyFrame_Type, "frame");
1789 INIT_TYPE(&PyCFunction_Type, "builtin function");
1790 INIT_TYPE(&PyMethod_Type, "method");
1791 INIT_TYPE(&PyFunction_Type, "function");
1792 INIT_TYPE(&PyDictProxy_Type, "dict proxy");
1793 INIT_TYPE(&PyGen_Type, "generator");
1794 INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
1795 INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
1796 INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
1797 INIT_TYPE(&PyEllipsis_Type, "ellipsis");
1798 INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
1799 INIT_TYPE(&_PyNamespace_Type, "namespace");
1800 INIT_TYPE(&PyCapsule_Type, "capsule");
1801 INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
1802 INIT_TYPE(&PyCell_Type, "cell");
1803 INIT_TYPE(&PyInstanceMethod_Type, "instance method");
1804 INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
1805 INIT_TYPE(&PyMethodDescr_Type, "method descr");
1806 INIT_TYPE(&PyCallIter_Type, "call iter");
1807 INIT_TYPE(&PySeqIter_Type, "sequence iterator");
1808 INIT_TYPE(&PyCoro_Type, "coroutine");
1809 INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
Eric Snowc11183c2019-03-15 16:35:46 -06001810 INIT_TYPE(&_PyInterpreterID_Type, "interpreter ID");
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001811 return _Py_INIT_OK();
Guido van Rossumba21a492001-08-16 08:17:26 +00001812
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001813#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001814}
1815
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001816
Guido van Rossum84a90321996-05-22 16:34:47 +00001817#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001818
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001819void
Fred Drake100814d2000-07-09 15:48:49 +00001820_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001821{
Victor Stinner9e00e802018-10-25 13:31:16 +02001822 if (_Py_tracemalloc_config.tracing) {
1823 _PyTraceMalloc_NewReference(op);
1824 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 _Py_INC_REFTOTAL;
1826 op->ob_refcnt = 1;
1827 _Py_AddToAllObjects(op, 1);
1828 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001829}
1830
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001831void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001832_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001833{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001834#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001835 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001836#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 if (op->ob_refcnt < 0)
1838 Py_FatalError("UNREF negative refcnt");
1839 if (op == &refchain ||
1840 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1841 fprintf(stderr, "* ob\n");
1842 _PyObject_Dump(op);
1843 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1844 _PyObject_Dump(op->_ob_prev->_ob_next);
1845 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1846 _PyObject_Dump(op->_ob_next->_ob_prev);
1847 Py_FatalError("UNREF invalid object");
1848 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001849#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1851 if (p == op)
1852 break;
1853 }
1854 if (p == &refchain) /* Not found */
1855 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001856#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 op->_ob_next->_ob_prev = op->_ob_prev;
1858 op->_ob_prev->_ob_next = op->_ob_next;
1859 op->_ob_next = op->_ob_prev = NULL;
1860 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001861}
1862
Tim Peters269b2a62003-04-17 19:52:29 +00001863/* Print all live objects. Because PyObject_Print is called, the
1864 * interpreter must be in a healthy state.
1865 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001866void
Fred Drake100814d2000-07-09 15:48:49 +00001867_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 PyObject *op;
1870 fprintf(fp, "Remaining objects:\n");
1871 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1872 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1873 if (PyObject_Print(op, fp, 0) != 0)
1874 PyErr_Clear();
1875 putc('\n', fp);
1876 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001877}
1878
Tim Peters269b2a62003-04-17 19:52:29 +00001879/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1880 * doesn't make any calls to the Python C API, so is always safe to call.
1881 */
1882void
1883_Py_PrintReferenceAddresses(FILE *fp)
1884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 PyObject *op;
1886 fprintf(fp, "Remaining object addresses:\n");
1887 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1888 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1889 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001890}
1891
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001892PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001893_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 int i, n;
1896 PyObject *t = NULL;
1897 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1900 return NULL;
1901 op = refchain._ob_next;
1902 res = PyList_New(0);
1903 if (res == NULL)
1904 return NULL;
1905 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1906 while (op == self || op == args || op == res || op == t ||
1907 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1908 op = op->_ob_next;
1909 if (op == &refchain)
1910 return res;
1911 }
1912 if (PyList_Append(res, op) < 0) {
1913 Py_DECREF(res);
1914 return NULL;
1915 }
1916 op = op->_ob_next;
1917 }
1918 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001919}
1920
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001921#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001922
Benjamin Petersonb173f782009-05-05 22:31:58 +00001923
Guido van Rossum84a90321996-05-22 16:34:47 +00001924/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001925Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001926
1927
David Malcolm49526f42012-06-22 14:55:41 -04001928void
1929_PyObject_DebugTypeStats(FILE *out)
1930{
1931 _PyCFunction_DebugMallocStats(out);
1932 _PyDict_DebugMallocStats(out);
1933 _PyFloat_DebugMallocStats(out);
1934 _PyFrame_DebugMallocStats(out);
1935 _PyList_DebugMallocStats(out);
1936 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001937 _PyTuple_DebugMallocStats(out);
1938}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001939
Guido van Rossum86610361998-04-10 22:32:46 +00001940/* These methods are used to control infinite recursion in repr, str, print,
1941 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00001942 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00001943 Py_ReprLeave() to avoid infinite recursion.
1944
1945 Py_ReprEnter() returns 0 the first time it is called for a particular
1946 object and 1 every time thereafter. It returns -1 if an exception
1947 occurred. Py_ReprLeave() has no return value.
1948
1949 See dictobject.c and listobject.c for examples of use.
1950*/
1951
Guido van Rossum86610361998-04-10 22:32:46 +00001952int
Fred Drake100814d2000-07-09 15:48:49 +00001953Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 PyObject *dict;
1956 PyObject *list;
1957 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02001960 /* Ignore a missing thread-state, so that this function can be called
1961 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 if (dict == NULL)
1963 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001964 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001966 if (PyErr_Occurred()) {
1967 return -1;
1968 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 list = PyList_New(0);
1970 if (list == NULL)
1971 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001972 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 return -1;
1974 Py_DECREF(list);
1975 }
1976 i = PyList_GET_SIZE(list);
1977 while (--i >= 0) {
1978 if (PyList_GET_ITEM(list, i) == obj)
1979 return 1;
1980 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02001981 if (PyList_Append(list, obj) < 0)
1982 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001984}
1985
1986void
Fred Drake100814d2000-07-09 15:48:49 +00001987Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyObject *dict;
1990 PyObject *list;
1991 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02001992 PyObject *error_type, *error_value, *error_traceback;
1993
1994 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 dict = PyThreadState_GetDict();
1997 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02001998 goto finally;
1999
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002000 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002002 goto finally;
2003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 i = PyList_GET_SIZE(list);
2005 /* Count backwards because we always expect obj to be list[-1] */
2006 while (--i >= 0) {
2007 if (PyList_GET_ITEM(list, i) == obj) {
2008 PyList_SetSlice(list, i, i + 1, NULL);
2009 break;
2010 }
2011 }
Victor Stinner1b634932013-07-16 22:24:44 +02002012
2013finally:
2014 /* ignore exceptions because there is no way to report them. */
2015 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002016}
Guido van Rossumd724b232000-03-13 16:01:29 +00002017
Tim Peters803526b2002-07-07 05:13:56 +00002018/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002019
Tim Peters803526b2002-07-07 05:13:56 +00002020/* Add op to the _PyTrash_delete_later list. Called when the current
2021 * call-stack depth gets large. op must be a currently untracked gc'ed
2022 * object, with refcount 0. Py_DECREF must already have been called on it.
2023 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002024void
Fred Drake100814d2000-07-09 15:48:49 +00002025_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002026{
Victor Stinner24702042018-10-26 17:16:37 +02002027 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2028 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2029 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002030 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002031 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002032}
2033
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002034/* The equivalent API, using per-thread state recursion info */
2035void
2036_PyTrash_thread_deposit_object(PyObject *op)
2037{
Victor Stinner50b48572018-11-01 01:51:40 +01002038 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002039 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2040 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2041 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002042 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002043 tstate->trash_delete_later = op;
2044}
2045
Tim Peters803526b2002-07-07 05:13:56 +00002046/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2047 * the call-stack unwinds again.
2048 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002049void
Fred Drake100814d2000-07-09 15:48:49 +00002050_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002051{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002052 while (_PyRuntime.gc.trash_delete_later) {
2053 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002055
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002056 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002057 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 /* Call the deallocator directly. This used to try to
2060 * fool Py_DECREF into calling it indirectly, but
2061 * Py_DECREF was already called on this object, and in
2062 * assorted non-release builds calling Py_DECREF again ends
2063 * up distorting allocation statistics.
2064 */
Victor Stinner24702042018-10-26 17:16:37 +02002065 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002066 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002068 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002070}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002071
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002072/* The equivalent API, using per-thread state recursion info */
2073void
2074_PyTrash_thread_destroy_chain(void)
2075{
Victor Stinner50b48572018-11-01 01:51:40 +01002076 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002077 /* We need to increase trash_delete_nesting here, otherwise,
2078 _PyTrash_thread_destroy_chain will be called recursively
2079 and then possibly crash. An example that may crash without
2080 increase:
2081 N = 500000 # need to be large enough
2082 ob = object()
2083 tups = [(ob,) for i in range(N)]
2084 for i in range(49):
2085 tups = [(tup,) for tup in tups]
2086 del tups
2087 */
2088 assert(tstate->trash_delete_nesting == 0);
2089 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002090 while (tstate->trash_delete_later) {
2091 PyObject *op = tstate->trash_delete_later;
2092 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2093
2094 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002095 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002096
2097 /* Call the deallocator directly. This used to try to
2098 * fool Py_DECREF into calling it indirectly, but
2099 * Py_DECREF was already called on this object, and in
2100 * assorted non-release builds calling Py_DECREF again ends
2101 * up distorting allocation statistics.
2102 */
Victor Stinner24702042018-10-26 17:16:37 +02002103 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002104 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002105 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002106 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002107 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002108}
2109
Victor Stinner626bff82018-10-25 17:31:10 +02002110
2111void
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002112_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002113 const char *file, int line, const char *function)
2114{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002115 fprintf(stderr, "%s:%d: ", file, line);
2116 if (function) {
2117 fprintf(stderr, "%s: ", function);
2118 }
Victor Stinner626bff82018-10-25 17:31:10 +02002119 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002120 if (expr) {
2121 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002122 }
2123 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002124 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002125 }
2126 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002127 if (msg) {
2128 fprintf(stderr, ": %s", msg);
2129 }
2130 fprintf(stderr, "\n");
2131 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002132
2133 if (obj == NULL) {
2134 fprintf(stderr, "<NULL object>\n");
2135 }
2136 else if (_PyObject_IsFreed(obj)) {
2137 /* It seems like the object memory has been freed:
2138 don't access it to prevent a segmentation fault. */
2139 fprintf(stderr, "<Freed object>\n");
2140 }
2141 else {
2142 /* Diplay the traceback where the object has been allocated.
2143 Do it before dumping repr(obj), since repr() is more likely
2144 to crash than dumping the traceback. */
2145 void *ptr;
2146 PyTypeObject *type = Py_TYPE(obj);
2147 if (PyType_IS_GC(type)) {
2148 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2149 }
2150 else {
2151 ptr = (void *)obj;
2152 }
2153 _PyMem_DumpTraceback(fileno(stderr), ptr);
2154
2155 /* This might succeed or fail, but we're about to abort, so at least
2156 try to provide any extra info we can: */
2157 _PyObject_Dump(obj);
2158 }
2159 fflush(stderr);
2160
2161 Py_FatalError("_PyObject_AssertFailed");
2162}
2163
Victor Stinner3c09dca2018-10-30 14:48:26 +01002164
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002165#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002166
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002167void
2168_Py_Dealloc(PyObject *op)
2169{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002170 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2171#ifdef Py_TRACE_REFS
2172 _Py_ForgetReference(op);
2173#else
2174 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002175#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002176 (*dealloc)(op);
2177}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002178
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002179#ifdef __cplusplus
2180}
2181#endif