blob: cf5264b5d80baf9029bd09e78f1187a5da8b1340 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Benjamin Peterson722954a2011-06-11 16:33:35 -05002/* Generic object operations; and implementation of None */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pystate.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01006#include "pycore_context.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00007#include "frameobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009#ifdef __cplusplus
10extern "C" {
11#endif
12
Victor Stinner626bff82018-10-25 17:31:10 +020013/* Defined in tracemalloc.c */
14extern void _PyMem_DumpTraceback(int fd, const void *ptr);
15
Victor Stinnerbd303c12013-11-07 23:07:29 +010016_Py_IDENTIFIER(Py_Repr);
17_Py_IDENTIFIER(__bytes__);
18_Py_IDENTIFIER(__dir__);
19_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010020
Tim Peters34592512002-07-11 06:23:50 +000021#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000022Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023
24Py_ssize_t
25_Py_GetRefTotal(void)
26{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 PyObject *o;
28 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020029 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030 if (o != NULL)
31 total -= o->ob_refcnt;
32 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000033}
Nick Coghland6009512014-11-20 21:39:37 +100034
35void
36_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070037 fprintf(stderr,
38 "[%" PY_FORMAT_SIZE_T "d refs, "
39 "%" PY_FORMAT_SIZE_T "d blocks]\n",
40 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100041}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000043
Guido van Rossum3f5da241990-12-20 15:06:42 +000044/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
45 These are used by the individual routines for object creation.
46 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000047
Tim Peters78be7992003-03-23 02:51:01 +000048#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000049/* Head of circular doubly-linked list of all objects. These are linked
50 * together via the _ob_prev and _ob_next members of a PyObject, which
51 * exist only in a Py_TRACE_REFS build.
52 */
Tim Peters78be7992003-03-23 02:51:01 +000053static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000054
Tim Peters7571a0f2003-03-23 17:52:28 +000055/* Insert op at the front of the list of all objects. If force is true,
56 * op is added even if _ob_prev and _ob_next are non-NULL already. If
57 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
58 * force should be true if and only if op points to freshly allocated,
59 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000060 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000061 * Note that objects are normally added to the list via _Py_NewReference,
62 * which is called by PyObject_Init. Not all objects are initialized that
63 * way, though; exceptions include statically allocated type objects, and
64 * statically allocated singletons (like Py_True and Py_None).
65 */
Tim Peters36eb4df2003-03-23 03:33:13 +000066void
Tim Peters7571a0f2003-03-23 17:52:28 +000067_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000068{
Tim Peters7571a0f2003-03-23 17:52:28 +000069#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 if (!force) {
71 /* If it's initialized memory, op must be in or out of
72 * the list unambiguously.
73 */
Victor Stinner24702042018-10-26 17:16:37 +020074 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 }
Tim Peters78be7992003-03-23 02:51:01 +000076#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 if (force || op->_ob_prev == NULL) {
78 op->_ob_next = refchain._ob_next;
79 op->_ob_prev = &refchain;
80 refchain._ob_next->_ob_prev = op;
81 refchain._ob_next = op;
82 }
Tim Peters7571a0f2003-03-23 17:52:28 +000083}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000085
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000086#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000087static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088/* All types are added to type_list, at least when
89 they get one object created. That makes them
90 immortal, which unfortunately contributes to
91 garbage itself. If unlist_types_without_objects
92 is set, they will be removed from the type_list
93 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +000094static int unlist_types_without_objects;
Pablo Galindo49c75a82018-10-28 15:02:17 +000095extern Py_ssize_t _Py_tuple_zero_allocs, _Py_fast_tuple_allocs;
96extern Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
97extern Py_ssize_t _Py_null_strings, _Py_one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000098void
Pablo Galindo49c75a82018-10-28 15:02:17 +000099_Py_dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000100{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200101 PyInterpreterState *interp = _PyInterpreterState_Get();
Eddie Elizondo745dc652018-02-21 20:55:18 -0800102 if (!interp->core_config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300103 return;
Victor Stinner25420fe2017-11-20 18:12:22 -0800104 }
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000105
Eddie Elizondo745dc652018-02-21 20:55:18 -0800106 PyTypeObject *tp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 for (tp = type_list; tp; tp = tp->tp_next)
108 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
109 "freed: %" PY_FORMAT_SIZE_T "d, "
110 "max in use: %" PY_FORMAT_SIZE_T "d\n",
111 tp->tp_name, tp->tp_allocs, tp->tp_frees,
112 tp->tp_maxalloc);
113 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
114 "empty: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000115 _Py_fast_tuple_allocs, _Py_tuple_zero_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
117 "neg: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000118 _Py_quick_int_allocs, _Py_quick_neg_int_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
120 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000121 _Py_null_strings, _Py_one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000122}
123
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000124PyObject *
Pablo Galindo49c75a82018-10-28 15:02:17 +0000125_Py_get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyTypeObject *tp;
128 PyObject *result;
129 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 result = PyList_New(0);
132 if (result == NULL)
133 return NULL;
134 for (tp = type_list; tp; tp = tp->tp_next) {
135 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
136 tp->tp_frees, tp->tp_maxalloc);
137 if (v == NULL) {
138 Py_DECREF(result);
139 return NULL;
140 }
141 if (PyList_Append(result, v) < 0) {
142 Py_DECREF(v);
143 Py_DECREF(result);
144 return NULL;
145 }
146 Py_DECREF(v);
147 }
148 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000149}
150
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000151void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000152_Py_inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
155 /* first time; insert in linked list */
156 if (tp->tp_next != NULL) /* sanity check */
Pablo Galindo49c75a82018-10-28 15:02:17 +0000157 Py_FatalError("XXX _Py_inc_count sanity check");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 if (type_list)
159 type_list->tp_prev = tp;
160 tp->tp_next = type_list;
161 /* Note that as of Python 2.2, heap-allocated type objects
162 * can go away, but this code requires that they stay alive
163 * until program exit. That's why we're careful with
164 * refcounts here. type_list gets a new reference to tp,
165 * while ownership of the reference type_list used to hold
166 * (if any) was transferred to tp->tp_next in the line above.
167 * tp is thus effectively immortal after this.
168 */
169 Py_INCREF(tp);
170 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000171#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 /* Also insert in the doubly-linked list of all objects,
173 * if not already there.
174 */
175 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000176#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 }
178 tp->tp_allocs++;
179 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
180 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000181}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000182
Pablo Galindo49c75a82018-10-28 15:02:17 +0000183void _Py_dec_count(PyTypeObject *tp)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 tp->tp_frees++;
186 if (unlist_types_without_objects &&
187 tp->tp_allocs == tp->tp_frees) {
188 /* unlink the type from type_list */
189 if (tp->tp_prev)
190 tp->tp_prev->tp_next = tp->tp_next;
191 else
192 type_list = tp->tp_next;
193 if (tp->tp_next)
194 tp->tp_next->tp_prev = tp->tp_prev;
195 tp->tp_next = tp->tp_prev = NULL;
196 Py_DECREF(tp);
197 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198}
199
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000200#endif
201
Tim Peters7c321a82002-07-09 02:57:01 +0000202#ifdef Py_REF_DEBUG
203/* Log a fatal error; doesn't return. */
204void
Victor Stinner18618e652018-10-25 17:28:11 +0200205_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000206{
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100207 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200208 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000209}
210
211#endif /* Py_REF_DEBUG */
212
Thomas Heller1328b522004-04-22 17:23:49 +0000213void
214Py_IncRef(PyObject *o)
215{
216 Py_XINCREF(o);
217}
218
219void
220Py_DecRef(PyObject *o)
221{
222 Py_XDECREF(o);
223}
224
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000225PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000226PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 if (op == NULL)
229 return PyErr_NoMemory();
230 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
231 Py_TYPE(op) = tp;
232 _Py_NewReference(op);
233 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234}
235
Guido van Rossumb18618d2000-05-03 23:44:39 +0000236PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000237PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (op == NULL)
240 return (PyVarObject *) PyErr_NoMemory();
241 /* Any changes should be reflected in PyObject_INIT_VAR */
242 op->ob_size = size;
243 Py_TYPE(op) = tp;
244 _Py_NewReference((PyObject *)op);
245 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000246}
247
248PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000249_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 PyObject *op;
252 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
253 if (op == NULL)
254 return PyErr_NoMemory();
255 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000256}
257
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000258PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000259_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyVarObject *op;
262 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
263 op = (PyVarObject *) PyObject_MALLOC(size);
264 if (op == NULL)
265 return (PyVarObject *)PyErr_NoMemory();
266 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000267}
268
Antoine Pitrou796564c2013-07-30 19:59:21 +0200269void
270PyObject_CallFinalizer(PyObject *self)
271{
272 PyTypeObject *tp = Py_TYPE(self);
273
274 /* The former could happen on heaptypes created from the C API, e.g.
275 PyType_FromSpec(). */
276 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
277 tp->tp_finalize == NULL)
278 return;
279 /* tp_finalize should only be called once. */
280 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
281 return;
282
283 tp->tp_finalize(self);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900284 if (PyType_IS_GC(tp)) {
285 _PyGC_SET_FINALIZED(self);
286 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200287}
288
289int
290PyObject_CallFinalizerFromDealloc(PyObject *self)
291{
292 Py_ssize_t refcnt;
293
294 /* Temporarily resurrect the object. */
295 if (self->ob_refcnt != 0) {
296 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
297 "object with a non-zero refcount");
298 }
299 self->ob_refcnt = 1;
300
301 PyObject_CallFinalizer(self);
302
303 /* Undo the temporary resurrection; can't use DECREF here, it would
304 * cause a recursive call.
305 */
Victor Stinner24702042018-10-26 17:16:37 +0200306 _PyObject_ASSERT_WITH_MSG(self,
307 self->ob_refcnt > 0,
308 "refcount is too small");
Antoine Pitrou796564c2013-07-30 19:59:21 +0200309 if (--self->ob_refcnt == 0)
310 return 0; /* this is the normal path out */
311
312 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
313 * never happened.
314 */
315 refcnt = self->ob_refcnt;
316 _Py_NewReference(self);
317 self->ob_refcnt = refcnt;
318
Victor Stinner24702042018-10-26 17:16:37 +0200319 _PyObject_ASSERT(self,
320 (!PyType_IS_GC(Py_TYPE(self))
321 || _PyObject_GC_IS_TRACKED(self)));
Antoine Pitrou796564c2013-07-30 19:59:21 +0200322 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
323 * we need to undo that. */
324 _Py_DEC_REFTOTAL;
325 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
326 * chain, so no more to do there.
327 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
328 * _Py_NewReference bumped tp_allocs: both of those need to be
329 * undone.
330 */
331#ifdef COUNT_ALLOCS
332 --Py_TYPE(self)->tp_frees;
333 --Py_TYPE(self)->tp_allocs;
334#endif
335 return -1;
336}
337
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000338int
339PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (PyErr_CheckSignals())
343 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000344#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 if (PyOS_CheckStack()) {
346 PyErr_SetString(PyExc_MemoryError, "stack overflow");
347 return -1;
348 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000349#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 clearerr(fp); /* Clear any previous error condition */
351 if (op == NULL) {
352 Py_BEGIN_ALLOW_THREADS
353 fprintf(fp, "<nil>");
354 Py_END_ALLOW_THREADS
355 }
356 else {
Victor Stinner3ec9af72018-10-26 02:12:34 +0200357 if (op->ob_refcnt <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 /* XXX(twouters) cast refcount to long until %zd is
359 universally available */
360 Py_BEGIN_ALLOW_THREADS
361 fprintf(fp, "<refcnt %ld at %p>",
362 (long)op->ob_refcnt, op);
363 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 else {
366 PyObject *s;
367 if (flags & Py_PRINT_RAW)
368 s = PyObject_Str(op);
369 else
370 s = PyObject_Repr(op);
371 if (s == NULL)
372 ret = -1;
373 else if (PyBytes_Check(s)) {
374 fwrite(PyBytes_AS_STRING(s), 1,
375 PyBytes_GET_SIZE(s), fp);
376 }
377 else if (PyUnicode_Check(s)) {
378 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200379 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600380 if (t == NULL) {
381 ret = -1;
382 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 else {
384 fwrite(PyBytes_AS_STRING(t), 1,
385 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000386 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 }
388 }
389 else {
390 PyErr_Format(PyExc_TypeError,
391 "str() or repr() returned '%.100s'",
392 s->ob_type->tp_name);
393 ret = -1;
394 }
395 Py_XDECREF(s);
396 }
397 }
398 if (ret == 0) {
399 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300400 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 clearerr(fp);
402 ret = -1;
403 }
404 }
405 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000406}
407
Guido van Rossum38938152006-08-21 23:36:26 +0000408/* For debugging convenience. Set a breakpoint here and call it from your DLL */
409void
Thomas Woutersb2137042007-02-01 18:02:27 +0000410_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000411{
412}
413
Neal Norwitz1a997502003-01-13 20:13:12 +0000414
Victor Stinner82af0b62018-10-23 17:39:40 +0200415/* Heuristic checking if the object memory has been deallocated.
416 Rely on the debug hooks on Python memory allocators which fills the memory
417 with DEADBYTE (0xDB) when memory is deallocated.
418
419 The function can be used to prevent segmentation fault on dereferencing
420 pointers like 0xdbdbdbdbdbdbdbdb. Such pointer is very unlikely to be mapped
421 in memory. */
422int
423_PyObject_IsFreed(PyObject *op)
424{
Victor Stinner2cf5d322018-11-22 16:32:57 +0100425 uintptr_t ptr = (uintptr_t)op;
426 if (_PyMem_IsFreed(&ptr, sizeof(ptr))) {
427 return 1;
428 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200429 int freed = _PyMem_IsFreed(&op->ob_type, sizeof(op->ob_type));
430 /* ignore op->ob_ref: the value can have be modified
431 by Py_INCREF() and Py_DECREF(). */
432#ifdef Py_TRACE_REFS
433 freed &= _PyMem_IsFreed(&op->_ob_next, sizeof(op->_ob_next));
434 freed &= _PyMem_IsFreed(&op->_ob_prev, sizeof(op->_ob_prev));
435#endif
436 return freed;
437}
438
439
Barry Warsaw9bf16442001-01-23 16:24:35 +0000440/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000441void
442_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000443{
Victor Stinner82af0b62018-10-23 17:39:40 +0200444 if (op == NULL) {
445 fprintf(stderr, "<NULL object>\n");
446 fflush(stderr);
447 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200449
450 if (_PyObject_IsFreed(op)) {
451 /* It seems like the object memory has been freed:
452 don't access it to prevent a segmentation fault. */
453 fprintf(stderr, "<freed object>\n");
Victor Stinner2cf5d322018-11-22 16:32:57 +0100454 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200455 }
456
457 PyGILState_STATE gil;
458 PyObject *error_type, *error_value, *error_traceback;
459
460 fprintf(stderr, "object : ");
461 fflush(stderr);
462 gil = PyGILState_Ensure();
463
464 PyErr_Fetch(&error_type, &error_value, &error_traceback);
465 (void)PyObject_Print(op, stderr, 0);
466 fflush(stderr);
467 PyErr_Restore(error_type, error_value, error_traceback);
468
469 PyGILState_Release(gil);
470 /* XXX(twouters) cast refcount to long until %zd is
471 universally available */
472 fprintf(stderr, "\n"
473 "type : %s\n"
474 "refcount: %ld\n"
475 "address : %p\n",
476 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
477 (long)op->ob_refcnt,
478 op);
479 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000480}
Barry Warsaw903138f2001-01-23 16:33:18 +0000481
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000483PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 PyObject *res;
486 if (PyErr_CheckSignals())
487 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000488#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (PyOS_CheckStack()) {
490 PyErr_SetString(PyExc_MemoryError, "stack overflow");
491 return NULL;
492 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000493#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (v == NULL)
495 return PyUnicode_FromString("<NULL>");
496 if (Py_TYPE(v)->tp_repr == NULL)
497 return PyUnicode_FromFormat("<%s object at %p>",
498 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200499
500#ifdef Py_DEBUG
501 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100502 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000503 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200504 assert(!PyErr_Occurred());
505#endif
506
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200507 /* It is possible for a type to have a tp_repr representation that loops
508 infinitely. */
509 if (Py_EnterRecursiveCall(" while getting the repr of an object"))
510 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 res = (*v->ob_type->tp_repr)(v);
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200512 Py_LeaveRecursiveCall();
Victor Stinner0a54cf12011-12-01 03:22:44 +0100513 if (res == NULL)
514 return NULL;
515 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyErr_Format(PyExc_TypeError,
517 "__repr__ returned non-string (type %.200s)",
518 res->ob_type->tp_name);
519 Py_DECREF(res);
520 return NULL;
521 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100522#ifndef Py_DEBUG
523 if (PyUnicode_READY(res) < 0)
524 return NULL;
525#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000527}
528
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000529PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000530PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyObject *res;
533 if (PyErr_CheckSignals())
534 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000535#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (PyOS_CheckStack()) {
537 PyErr_SetString(PyExc_MemoryError, "stack overflow");
538 return NULL;
539 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000540#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (v == NULL)
542 return PyUnicode_FromString("<NULL>");
543 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100544#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100545 if (PyUnicode_READY(v) < 0)
546 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100547#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_INCREF(v);
549 return v;
550 }
551 if (Py_TYPE(v)->tp_str == NULL)
552 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000553
Victor Stinner33824f62013-08-26 14:05:19 +0200554#ifdef Py_DEBUG
555 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100556 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000557 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200558 assert(!PyErr_Occurred());
559#endif
560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 /* It is possible for a type to have a tp_str representation that loops
562 infinitely. */
563 if (Py_EnterRecursiveCall(" while getting the str of an object"))
564 return NULL;
565 res = (*Py_TYPE(v)->tp_str)(v);
566 Py_LeaveRecursiveCall();
567 if (res == NULL)
568 return NULL;
569 if (!PyUnicode_Check(res)) {
570 PyErr_Format(PyExc_TypeError,
571 "__str__ returned non-string (type %.200s)",
572 Py_TYPE(res)->tp_name);
573 Py_DECREF(res);
574 return NULL;
575 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100576#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100577 if (PyUnicode_READY(res) < 0)
578 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100579#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100580 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000582}
583
Georg Brandl559e5d72008-06-11 18:37:52 +0000584PyObject *
585PyObject_ASCII(PyObject *v)
586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 repr = PyObject_Repr(v);
590 if (repr == NULL)
591 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000592
Victor Stinneraf037572013-04-14 18:44:10 +0200593 if (PyUnicode_IS_ASCII(repr))
594 return repr;
595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200597 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 Py_DECREF(repr);
599 if (ascii == NULL)
600 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 res = PyUnicode_DecodeASCII(
603 PyBytes_AS_STRING(ascii),
604 PyBytes_GET_SIZE(ascii),
605 NULL);
606
607 Py_DECREF(ascii);
608 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000609}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000610
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000611PyObject *
612PyObject_Bytes(PyObject *v)
613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (v == NULL)
617 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (PyBytes_CheckExact(v)) {
620 Py_INCREF(v);
621 return v;
622 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000623
Benjamin Petersonce798522012-01-22 11:24:29 -0500624 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100626 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 Py_DECREF(func);
628 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000629 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000631 PyErr_Format(PyExc_TypeError,
632 "__bytes__ returned non-bytes (type %.200s)",
633 Py_TYPE(result)->tp_name);
634 Py_DECREF(result);
635 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 }
637 return result;
638 }
639 else if (PyErr_Occurred())
640 return NULL;
641 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000642}
643
Mark Dickinsonc008a172009-02-01 13:59:22 +0000644/* For Python 3.0.1 and later, the old three-way comparison has been
645 completely removed in favour of rich comparisons. PyObject_Compare() and
646 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000647 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000648 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000649
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000650 See (*) below for practical amendments.
651
Mark Dickinsonc008a172009-02-01 13:59:22 +0000652 tp_richcompare gets called with a first argument of the appropriate type
653 and a second object of an arbitrary type. We never do any kind of
654 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000655
Mark Dickinsonc008a172009-02-01 13:59:22 +0000656 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000657
658 NULL if an exception occurred
659 NotImplemented if the requested comparison is not implemented
660 any other false value if the requested comparison is false
661 any other true value if the requested comparison is true
662
663 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
664 NotImplemented.
665
666 (*) Practical amendments:
667
668 - If rich comparison returns NotImplemented, == and != are decided by
669 comparing the object pointer (i.e. falling back to the base object
670 implementation).
671
Guido van Rossuma4073002002-05-31 20:03:54 +0000672*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000673
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000674/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000675int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000676
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200677static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000678
679/* Perform a rich comparison, raising TypeError when the requested comparison
680 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000681static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000682do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 richcmpfunc f;
685 PyObject *res;
686 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (v->ob_type != w->ob_type &&
689 PyType_IsSubtype(w->ob_type, v->ob_type) &&
690 (f = w->ob_type->tp_richcompare) != NULL) {
691 checked_reverse_op = 1;
692 res = (*f)(w, v, _Py_SwappedOp[op]);
693 if (res != Py_NotImplemented)
694 return res;
695 Py_DECREF(res);
696 }
697 if ((f = v->ob_type->tp_richcompare) != NULL) {
698 res = (*f)(v, w, op);
699 if (res != Py_NotImplemented)
700 return res;
701 Py_DECREF(res);
702 }
703 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
704 res = (*f)(w, v, _Py_SwappedOp[op]);
705 if (res != Py_NotImplemented)
706 return res;
707 Py_DECREF(res);
708 }
709 /* If neither object implements it, provide a sensible default
710 for == and !=, but raise an exception for ordering. */
711 switch (op) {
712 case Py_EQ:
713 res = (v == w) ? Py_True : Py_False;
714 break;
715 case Py_NE:
716 res = (v != w) ? Py_True : Py_False;
717 break;
718 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyErr_Format(PyExc_TypeError,
Victor Stinner91108f02015-10-14 18:25:31 +0200720 "'%s' not supported between instances of '%.100s' and '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 opstrings[op],
Victor Stinner91108f02015-10-14 18:25:31 +0200722 v->ob_type->tp_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 w->ob_type->tp_name);
724 return NULL;
725 }
726 Py_INCREF(res);
727 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000728}
729
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000730/* Perform a rich comparison with object result. This wraps do_richcompare()
731 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000732
Guido van Rossume797ec12001-01-17 15:24:28 +0000733PyObject *
734PyObject_RichCompare(PyObject *v, PyObject *w, int op)
735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 assert(Py_LT <= op && op <= Py_GE);
739 if (v == NULL || w == NULL) {
740 if (!PyErr_Occurred())
741 PyErr_BadInternalCall();
742 return NULL;
743 }
744 if (Py_EnterRecursiveCall(" in comparison"))
745 return NULL;
746 res = do_richcompare(v, w, op);
747 Py_LeaveRecursiveCall();
748 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000749}
750
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000751/* Perform a rich comparison with integer result. This wraps
752 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000753int
754PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyObject *res;
757 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* Quick result when objects are the same.
760 Guarantees that identity implies equality. */
761 if (v == w) {
762 if (op == Py_EQ)
763 return 1;
764 else if (op == Py_NE)
765 return 0;
766 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 res = PyObject_RichCompare(v, w, op);
769 if (res == NULL)
770 return -1;
771 if (PyBool_Check(res))
772 ok = (res == Py_True);
773 else
774 ok = PyObject_IsTrue(res);
775 Py_DECREF(res);
776 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000777}
Fred Drake13634cf2000-06-29 19:17:04 +0000778
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100779Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000780PyObject_HashNotImplemented(PyObject *v)
781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
783 Py_TYPE(v)->tp_name);
784 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000785}
Fred Drake13634cf2000-06-29 19:17:04 +0000786
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000787Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000788PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyTypeObject *tp = Py_TYPE(v);
791 if (tp->tp_hash != NULL)
792 return (*tp->tp_hash)(v);
793 /* To keep to the general practice that inheriting
794 * solely from object in C code should work without
795 * an explicit call to PyType_Ready, we implicitly call
796 * PyType_Ready here and then check the tp_hash slot again
797 */
798 if (tp->tp_dict == NULL) {
799 if (PyType_Ready(tp) < 0)
800 return -1;
801 if (tp->tp_hash != NULL)
802 return (*tp->tp_hash)(v);
803 }
804 /* Otherwise, the object can't be hashed */
805 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000806}
807
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000808PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000809PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (Py_TYPE(v)->tp_getattr != NULL)
814 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900815 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (w == NULL)
817 return NULL;
818 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100819 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000821}
822
823int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000824PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyObject *res = PyObject_GetAttrString(v, name);
827 if (res != NULL) {
828 Py_DECREF(res);
829 return 1;
830 }
831 PyErr_Clear();
832 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000833}
834
835int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000836PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyObject *s;
839 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (Py_TYPE(v)->tp_setattr != NULL)
842 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
843 s = PyUnicode_InternFromString(name);
844 if (s == NULL)
845 return -1;
846 res = PyObject_SetAttr(v, s, w);
847 Py_XDECREF(s);
848 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000849}
850
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500851int
852_PyObject_IsAbstract(PyObject *obj)
853{
854 int res;
855 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500856
857 if (obj == NULL)
858 return 0;
859
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200860 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
861 if (res > 0) {
862 res = PyObject_IsTrue(isabstract);
863 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500864 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500865 return res;
866}
867
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000868PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200869_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
870{
871 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100872 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200873 if (!oname)
874 return NULL;
875 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200876 return result;
877}
878
879int
880_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
881{
882 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100883 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200884 if (!oname)
885 return -1;
886 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200887 return result;
888}
889
890int
891_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
892{
893 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100894 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200895 if (!oname)
896 return -1;
897 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200898 return result;
899}
900
901PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000902PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (!PyUnicode_Check(name)) {
907 PyErr_Format(PyExc_TypeError,
908 "attribute name must be string, not '%.200s'",
909 name->ob_type->tp_name);
910 return NULL;
911 }
912 if (tp->tp_getattro != NULL)
913 return (*tp->tp_getattro)(v, name);
914 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200915 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (name_str == NULL)
917 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200918 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 }
920 PyErr_Format(PyExc_AttributeError,
921 "'%.50s' object has no attribute '%U'",
922 tp->tp_name, name);
923 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000924}
925
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200926int
927_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900928{
929 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900930
931 if (!PyUnicode_Check(name)) {
932 PyErr_Format(PyExc_TypeError,
933 "attribute name must be string, not '%.200s'",
934 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200935 *result = NULL;
936 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900937 }
938
939 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200940 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
941 if (*result != NULL) {
942 return 1;
943 }
944 if (PyErr_Occurred()) {
945 return -1;
946 }
947 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900948 }
949 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200950 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900951 }
952 else if (tp->tp_getattr != NULL) {
953 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200954 if (name_str == NULL) {
955 *result = NULL;
956 return -1;
957 }
958 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900959 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900960 else {
961 *result = NULL;
962 return 0;
963 }
964
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200965 if (*result != NULL) {
966 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900967 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200968 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
969 return -1;
970 }
971 PyErr_Clear();
972 return 0;
973}
974
975int
976_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
977{
978 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
979 if (!oname) {
980 *result = NULL;
981 return -1;
982 }
983 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +0900984}
985
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000986int
Fred Drake100814d2000-07-09 15:48:49 +0000987PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000988{
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200989 PyObject *res;
990 if (_PyObject_LookupAttr(v, name, &res) < 0) {
991 PyErr_Clear();
992 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200994 if (res == NULL) {
995 return 0;
996 }
997 Py_DECREF(res);
998 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000999}
1000
1001int
Fred Drake100814d2000-07-09 15:48:49 +00001002PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyTypeObject *tp = Py_TYPE(v);
1005 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (!PyUnicode_Check(name)) {
1008 PyErr_Format(PyExc_TypeError,
1009 "attribute name must be string, not '%.200s'",
1010 name->ob_type->tp_name);
1011 return -1;
1012 }
1013 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PyUnicode_InternInPlace(&name);
1016 if (tp->tp_setattro != NULL) {
1017 err = (*tp->tp_setattro)(v, name, value);
1018 Py_DECREF(name);
1019 return err;
1020 }
1021 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001022 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (name_str == NULL)
1024 return -1;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001025 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 Py_DECREF(name);
1027 return err;
1028 }
1029 Py_DECREF(name);
Victor Stinner24702042018-10-26 17:16:37 +02001030 _PyObject_ASSERT(name, name->ob_refcnt >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1032 PyErr_Format(PyExc_TypeError,
1033 "'%.100s' object has no attributes "
1034 "(%s .%U)",
1035 tp->tp_name,
1036 value==NULL ? "del" : "assign to",
1037 name);
1038 else
1039 PyErr_Format(PyExc_TypeError,
1040 "'%.100s' object has only read-only attributes "
1041 "(%s .%U)",
1042 tp->tp_name,
1043 value==NULL ? "del" : "assign to",
1044 name);
1045 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001046}
1047
1048/* Helper to get a pointer to an object's __dict__ slot, if any */
1049
1050PyObject **
1051_PyObject_GetDictPtr(PyObject *obj)
1052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 Py_ssize_t dictoffset;
1054 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 dictoffset = tp->tp_dictoffset;
1057 if (dictoffset == 0)
1058 return NULL;
1059 if (dictoffset < 0) {
1060 Py_ssize_t tsize;
1061 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 tsize = ((PyVarObject *)obj)->ob_size;
1064 if (tsize < 0)
1065 tsize = -tsize;
1066 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001069 _PyObject_ASSERT(obj, dictoffset > 0);
1070 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
1072 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001073}
1074
Tim Peters6d6c1a32001-08-02 04:15:00 +00001075PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001076PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 Py_INCREF(obj);
1079 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001080}
1081
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001082/* Helper used when the __next__ method is removed from a type:
1083 tp_iternext is never NULL and can be safely called without checking
1084 on every iteration.
1085 */
1086
1087PyObject *
1088_PyObject_NextNotImplemented(PyObject *self)
1089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyErr_Format(PyExc_TypeError,
1091 "'%.200s' object is not iterable",
1092 Py_TYPE(self)->tp_name);
1093 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001094}
1095
Yury Selivanovf2392132016-12-13 19:03:51 -05001096
1097/* Specialized version of _PyObject_GenericGetAttrWithDict
1098 specifically for the LOAD_METHOD opcode.
1099
1100 Return 1 if a method is found, 0 if it's a regular attribute
1101 from __dict__ or something returned by using a descriptor
1102 protocol.
1103
1104 `method` will point to the resolved attribute or NULL. In the
1105 latter case, an error will be set.
1106*/
1107int
1108_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1109{
1110 PyTypeObject *tp = Py_TYPE(obj);
1111 PyObject *descr;
1112 descrgetfunc f = NULL;
1113 PyObject **dictptr, *dict;
1114 PyObject *attr;
1115 int meth_found = 0;
1116
1117 assert(*method == NULL);
1118
1119 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1120 || !PyUnicode_Check(name)) {
1121 *method = PyObject_GetAttr(obj, name);
1122 return 0;
1123 }
1124
1125 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1126 return 0;
1127
1128 descr = _PyType_Lookup(tp, name);
1129 if (descr != NULL) {
1130 Py_INCREF(descr);
INADA Naoki5566bbb2017-02-03 07:43:03 +09001131 if (PyFunction_Check(descr) ||
1132 (Py_TYPE(descr) == &PyMethodDescr_Type)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001133 meth_found = 1;
1134 } else {
1135 f = descr->ob_type->tp_descr_get;
1136 if (f != NULL && PyDescr_IsData(descr)) {
1137 *method = f(descr, obj, (PyObject *)obj->ob_type);
1138 Py_DECREF(descr);
1139 return 0;
1140 }
1141 }
1142 }
1143
1144 dictptr = _PyObject_GetDictPtr(obj);
1145 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1146 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001147 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001148 if (attr != NULL) {
1149 Py_INCREF(attr);
1150 *method = attr;
1151 Py_DECREF(dict);
1152 Py_XDECREF(descr);
1153 return 0;
1154 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001155 else {
1156 Py_DECREF(dict);
1157 if (PyErr_Occurred()) {
1158 Py_XDECREF(descr);
1159 return 0;
1160 }
1161 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001162 }
1163
1164 if (meth_found) {
1165 *method = descr;
1166 return 1;
1167 }
1168
1169 if (f != NULL) {
1170 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1171 Py_DECREF(descr);
1172 return 0;
1173 }
1174
1175 if (descr != NULL) {
1176 *method = descr;
1177 return 0;
1178 }
1179
1180 PyErr_Format(PyExc_AttributeError,
1181 "'%.50s' object has no attribute '%U'",
1182 tp->tp_name, name);
1183 return 0;
1184}
1185
1186/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001187
Raymond Hettinger01538262003-03-17 08:24:35 +00001188PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001189_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1190 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001191{
Yury Selivanovf2392132016-12-13 19:03:51 -05001192 /* Make sure the logic of _PyObject_GetMethod is in sync with
1193 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001194
1195 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001196 */
1197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyTypeObject *tp = Py_TYPE(obj);
1199 PyObject *descr = NULL;
1200 PyObject *res = NULL;
1201 descrgetfunc f;
1202 Py_ssize_t dictoffset;
1203 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (!PyUnicode_Check(name)){
1206 PyErr_Format(PyExc_TypeError,
1207 "attribute name must be string, not '%.200s'",
1208 name->ob_type->tp_name);
1209 return NULL;
1210 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001211 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (tp->tp_dict == NULL) {
1214 if (PyType_Ready(tp) < 0)
1215 goto done;
1216 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 f = NULL;
1221 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001222 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 f = descr->ob_type->tp_descr_get;
1224 if (f != NULL && PyDescr_IsData(descr)) {
1225 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001226 if (res == NULL && suppress &&
1227 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1228 PyErr_Clear();
1229 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 goto done;
1231 }
1232 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001234 if (dict == NULL) {
1235 /* Inline _PyObject_GetDictPtr */
1236 dictoffset = tp->tp_dictoffset;
1237 if (dictoffset != 0) {
1238 if (dictoffset < 0) {
1239 Py_ssize_t tsize;
1240 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001241
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001242 tsize = ((PyVarObject *)obj)->ob_size;
1243 if (tsize < 0)
1244 tsize = -tsize;
1245 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001246 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001247
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001248 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001249 _PyObject_ASSERT(obj, dictoffset > 0);
1250 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001252 dictptr = (PyObject **) ((char *)obj + dictoffset);
1253 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 }
1255 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001256 if (dict != NULL) {
1257 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001258 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001259 if (res != NULL) {
1260 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001261 Py_DECREF(dict);
1262 goto done;
1263 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001264 else {
1265 Py_DECREF(dict);
1266 if (PyErr_Occurred()) {
1267 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1268 PyErr_Clear();
1269 }
1270 else {
1271 goto done;
1272 }
1273 }
1274 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001275 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (f != NULL) {
1278 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001279 if (res == NULL && suppress &&
1280 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1281 PyErr_Clear();
1282 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 goto done;
1284 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (descr != NULL) {
1287 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001288 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 goto done;
1290 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001291
INADA Naoki378edee2018-01-16 20:52:41 +09001292 if (!suppress) {
1293 PyErr_Format(PyExc_AttributeError,
1294 "'%.50s' object has no attribute '%U'",
1295 tp->tp_name, name);
1296 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001297 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001298 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 Py_DECREF(name);
1300 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301}
1302
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001303PyObject *
1304PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1305{
INADA Naoki378edee2018-01-16 20:52:41 +09001306 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001307}
1308
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001310_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1311 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 PyTypeObject *tp = Py_TYPE(obj);
1314 PyObject *descr;
1315 descrsetfunc f;
1316 PyObject **dictptr;
1317 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (!PyUnicode_Check(name)){
1320 PyErr_Format(PyExc_TypeError,
1321 "attribute name must be string, not '%.200s'",
1322 name->ob_type->tp_name);
1323 return -1;
1324 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001325
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001326 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1327 return -1;
1328
1329 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001334 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001336 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 res = f(descr, obj, value);
1338 goto done;
1339 }
1340 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001342 if (dict == NULL) {
1343 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001344 if (dictptr == NULL) {
1345 if (descr == NULL) {
1346 PyErr_Format(PyExc_AttributeError,
1347 "'%.100s' object has no attribute '%U'",
1348 tp->tp_name, name);
1349 }
1350 else {
1351 PyErr_Format(PyExc_AttributeError,
1352 "'%.50s' object attribute '%U' is read-only",
1353 tp->tp_name, name);
1354 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001355 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001357 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001358 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001359 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001360 Py_INCREF(dict);
1361 if (value == NULL)
1362 res = PyDict_DelItem(dict, name);
1363 else
1364 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001365 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001367 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1368 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001369
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001370 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001371 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 Py_DECREF(name);
1373 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001374}
1375
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001376int
1377PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1378{
1379 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1380}
1381
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001382int
1383PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1384{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001385 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001386 if (dictptr == NULL) {
1387 PyErr_SetString(PyExc_AttributeError,
1388 "This object has no __dict__");
1389 return -1;
1390 }
1391 if (value == NULL) {
1392 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1393 return -1;
1394 }
1395 if (!PyDict_Check(value)) {
1396 PyErr_Format(PyExc_TypeError,
1397 "__dict__ must be set to a dictionary, "
1398 "not a '%.200s'", Py_TYPE(value)->tp_name);
1399 return -1;
1400 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001401 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001402 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001403 return 0;
1404}
1405
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001406
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001407/* Test a value used as condition, e.g., in a for or if statement.
1408 Return -1 if an error occurred */
1409
1410int
Fred Drake100814d2000-07-09 15:48:49 +00001411PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 Py_ssize_t res;
1414 if (v == Py_True)
1415 return 1;
1416 if (v == Py_False)
1417 return 0;
1418 if (v == Py_None)
1419 return 0;
1420 else if (v->ob_type->tp_as_number != NULL &&
1421 v->ob_type->tp_as_number->nb_bool != NULL)
1422 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1423 else if (v->ob_type->tp_as_mapping != NULL &&
1424 v->ob_type->tp_as_mapping->mp_length != NULL)
1425 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1426 else if (v->ob_type->tp_as_sequence != NULL &&
1427 v->ob_type->tp_as_sequence->sq_length != NULL)
1428 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1429 else
1430 return 1;
1431 /* if it is negative, it should be either -1 or -2 */
1432 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001433}
1434
Tim Peters803526b2002-07-07 05:13:56 +00001435/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001436 Return -1 if an error occurred */
1437
1438int
Fred Drake100814d2000-07-09 15:48:49 +00001439PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 int res;
1442 res = PyObject_IsTrue(v);
1443 if (res < 0)
1444 return res;
1445 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001446}
1447
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001448/* Test whether an object can be called */
1449
1450int
Fred Drake100814d2000-07-09 15:48:49 +00001451PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (x == NULL)
1454 return 0;
1455 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001456}
1457
Tim Peters7eea37e2001-09-04 22:08:56 +00001458
Georg Brandle32b4222007-03-10 22:13:27 +00001459/* Helper for PyObject_Dir without arguments: returns the local scope. */
1460static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001461_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001464 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001465
Victor Stinner41bb43a2013-10-29 01:19:37 +01001466 locals = PyEval_GetLocals();
1467 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 names = PyMapping_Keys(locals);
1471 if (!names)
1472 return NULL;
1473 if (!PyList_Check(names)) {
1474 PyErr_Format(PyExc_TypeError,
1475 "dir(): expected keys() of locals to be a list, "
1476 "not '%.200s'", Py_TYPE(names)->tp_name);
1477 Py_DECREF(names);
1478 return NULL;
1479 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001480 if (PyList_Sort(names)) {
1481 Py_DECREF(names);
1482 return NULL;
1483 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 /* the locals don't need to be DECREF'd */
1485 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001486}
1487
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001488/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001489static PyObject *
1490_dir_object(PyObject *obj)
1491{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001492 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001493 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001494
Victor Stinner24702042018-10-26 17:16:37 +02001495 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001497 if (!PyErr_Occurred())
1498 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1499 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001501 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001502 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001503 Py_DECREF(dirfunc);
1504 if (result == NULL)
1505 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001506 /* return sorted(result) */
1507 sorted = PySequence_List(result);
1508 Py_DECREF(result);
1509 if (sorted == NULL)
1510 return NULL;
1511 if (PyList_Sort(sorted)) {
1512 Py_DECREF(sorted);
1513 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001515 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001516}
1517
1518/* Implementation of dir() -- if obj is NULL, returns the names in the current
1519 (local) scope. Otherwise, performs introspection of the object: returns a
1520 sorted list of attribute names (supposedly) accessible from the object
1521*/
1522PyObject *
1523PyObject_Dir(PyObject *obj)
1524{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001525 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001526}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001527
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001528/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001529None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001530There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001531so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001532*/
1533
Guido van Rossum0c182a11992-03-27 17:26:13 +00001534/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001535static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001536none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001539}
1540
Barry Warsaw9bf16442001-01-23 16:24:35 +00001541/* ARGUSED */
1542static void
Tim Peters803526b2002-07-07 05:13:56 +00001543none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 /* This should never get called, but we also don't want to SEGV if
1546 * we accidentally decref None out of existence.
1547 */
1548 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001549}
1550
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001551static PyObject *
1552none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1553{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001554 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001555 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1556 return NULL;
1557 }
1558 Py_RETURN_NONE;
1559}
1560
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001561static int
1562none_bool(PyObject *v)
1563{
1564 return 0;
1565}
1566
1567static PyNumberMethods none_as_number = {
1568 0, /* nb_add */
1569 0, /* nb_subtract */
1570 0, /* nb_multiply */
1571 0, /* nb_remainder */
1572 0, /* nb_divmod */
1573 0, /* nb_power */
1574 0, /* nb_negative */
1575 0, /* nb_positive */
1576 0, /* nb_absolute */
1577 (inquiry)none_bool, /* nb_bool */
1578 0, /* nb_invert */
1579 0, /* nb_lshift */
1580 0, /* nb_rshift */
1581 0, /* nb_and */
1582 0, /* nb_xor */
1583 0, /* nb_or */
1584 0, /* nb_int */
1585 0, /* nb_reserved */
1586 0, /* nb_float */
1587 0, /* nb_inplace_add */
1588 0, /* nb_inplace_subtract */
1589 0, /* nb_inplace_multiply */
1590 0, /* nb_inplace_remainder */
1591 0, /* nb_inplace_power */
1592 0, /* nb_inplace_lshift */
1593 0, /* nb_inplace_rshift */
1594 0, /* nb_inplace_and */
1595 0, /* nb_inplace_xor */
1596 0, /* nb_inplace_or */
1597 0, /* nb_floor_divide */
1598 0, /* nb_true_divide */
1599 0, /* nb_inplace_floor_divide */
1600 0, /* nb_inplace_true_divide */
1601 0, /* nb_index */
1602};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001603
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001604PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1606 "NoneType",
1607 0,
1608 0,
1609 none_dealloc, /*tp_dealloc*/ /*never called*/
1610 0, /*tp_print*/
1611 0, /*tp_getattr*/
1612 0, /*tp_setattr*/
1613 0, /*tp_reserved*/
1614 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001615 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 0, /*tp_as_sequence*/
1617 0, /*tp_as_mapping*/
1618 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001619 0, /*tp_call */
1620 0, /*tp_str */
1621 0, /*tp_getattro */
1622 0, /*tp_setattro */
1623 0, /*tp_as_buffer */
1624 Py_TPFLAGS_DEFAULT, /*tp_flags */
1625 0, /*tp_doc */
1626 0, /*tp_traverse */
1627 0, /*tp_clear */
1628 0, /*tp_richcompare */
1629 0, /*tp_weaklistoffset */
1630 0, /*tp_iter */
1631 0, /*tp_iternext */
1632 0, /*tp_methods */
1633 0, /*tp_members */
1634 0, /*tp_getset */
1635 0, /*tp_base */
1636 0, /*tp_dict */
1637 0, /*tp_descr_get */
1638 0, /*tp_descr_set */
1639 0, /*tp_dictoffset */
1640 0, /*tp_init */
1641 0, /*tp_alloc */
1642 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001643};
1644
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001645PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001646 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001647 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001648};
1649
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001650/* NotImplemented is an object that can be used to signal that an
1651 operation is not implemented for the given type combination. */
1652
1653static PyObject *
1654NotImplemented_repr(PyObject *op)
1655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001657}
1658
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001659static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301660NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001661{
1662 return PyUnicode_FromString("NotImplemented");
1663}
1664
1665static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301666 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001667 {NULL, NULL}
1668};
1669
1670static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001671notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1672{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001673 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001674 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1675 return NULL;
1676 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001677 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001678}
1679
Armin Ronacher226b1db2012-10-06 14:28:58 +02001680static void
1681notimplemented_dealloc(PyObject* ignore)
1682{
1683 /* This should never get called, but we also don't want to SEGV if
1684 * we accidentally decref NotImplemented out of existence.
1685 */
1686 Py_FatalError("deallocating NotImplemented");
1687}
1688
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001689PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1691 "NotImplementedType",
1692 0,
1693 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001694 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 0, /*tp_print*/
1696 0, /*tp_getattr*/
1697 0, /*tp_setattr*/
1698 0, /*tp_reserved*/
1699 NotImplemented_repr, /*tp_repr*/
1700 0, /*tp_as_number*/
1701 0, /*tp_as_sequence*/
1702 0, /*tp_as_mapping*/
1703 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001704 0, /*tp_call */
1705 0, /*tp_str */
1706 0, /*tp_getattro */
1707 0, /*tp_setattro */
1708 0, /*tp_as_buffer */
1709 Py_TPFLAGS_DEFAULT, /*tp_flags */
1710 0, /*tp_doc */
1711 0, /*tp_traverse */
1712 0, /*tp_clear */
1713 0, /*tp_richcompare */
1714 0, /*tp_weaklistoffset */
1715 0, /*tp_iter */
1716 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001717 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001718 0, /*tp_members */
1719 0, /*tp_getset */
1720 0, /*tp_base */
1721 0, /*tp_dict */
1722 0, /*tp_descr_get */
1723 0, /*tp_descr_set */
1724 0, /*tp_dictoffset */
1725 0, /*tp_init */
1726 0, /*tp_alloc */
1727 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001728};
1729
1730PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001732 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001733};
1734
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001735_PyInitError
Victor Stinnerab672812019-01-23 15:04:40 +01001736_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001737{
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001738#define INIT_TYPE(TYPE, NAME) \
1739 do { \
1740 if (PyType_Ready(TYPE) < 0) { \
1741 return _Py_INIT_ERR("Can't initialize " NAME " type"); \
1742 } \
1743 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001744
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001745 INIT_TYPE(&PyBaseObject_Type, "object");
1746 INIT_TYPE(&PyType_Type, "type");
1747 INIT_TYPE(&_PyWeakref_RefType, "weakref");
1748 INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
1749 INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
1750 INIT_TYPE(&PyLong_Type, "int");
1751 INIT_TYPE(&PyBool_Type, "bool");
1752 INIT_TYPE(&PyByteArray_Type, "bytearray");
1753 INIT_TYPE(&PyBytes_Type, "str");
1754 INIT_TYPE(&PyList_Type, "list");
1755 INIT_TYPE(&_PyNone_Type, "None");
1756 INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
1757 INIT_TYPE(&PyTraceBack_Type, "traceback");
1758 INIT_TYPE(&PySuper_Type, "super");
1759 INIT_TYPE(&PyRange_Type, "range");
1760 INIT_TYPE(&PyDict_Type, "dict");
1761 INIT_TYPE(&PyDictKeys_Type, "dict keys");
1762 INIT_TYPE(&PyDictValues_Type, "dict values");
1763 INIT_TYPE(&PyDictItems_Type, "dict items");
1764 INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
1765 INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
1766 INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
1767 INIT_TYPE(&PyODict_Type, "OrderedDict");
1768 INIT_TYPE(&PyODictKeys_Type, "odict_keys");
1769 INIT_TYPE(&PyODictItems_Type, "odict_items");
1770 INIT_TYPE(&PyODictValues_Type, "odict_values");
1771 INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
1772 INIT_TYPE(&PySet_Type, "set");
1773 INIT_TYPE(&PyUnicode_Type, "str");
1774 INIT_TYPE(&PySlice_Type, "slice");
1775 INIT_TYPE(&PyStaticMethod_Type, "static method");
1776 INIT_TYPE(&PyComplex_Type, "complex");
1777 INIT_TYPE(&PyFloat_Type, "float");
1778 INIT_TYPE(&PyFrozenSet_Type, "frozenset");
1779 INIT_TYPE(&PyProperty_Type, "property");
1780 INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
1781 INIT_TYPE(&PyMemoryView_Type, "memoryview");
1782 INIT_TYPE(&PyTuple_Type, "tuple");
1783 INIT_TYPE(&PyEnum_Type, "enumerate");
1784 INIT_TYPE(&PyReversed_Type, "reversed");
1785 INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
1786 INIT_TYPE(&PyCode_Type, "code");
1787 INIT_TYPE(&PyFrame_Type, "frame");
1788 INIT_TYPE(&PyCFunction_Type, "builtin function");
1789 INIT_TYPE(&PyMethod_Type, "method");
1790 INIT_TYPE(&PyFunction_Type, "function");
1791 INIT_TYPE(&PyDictProxy_Type, "dict proxy");
1792 INIT_TYPE(&PyGen_Type, "generator");
1793 INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
1794 INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
1795 INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
1796 INIT_TYPE(&PyEllipsis_Type, "ellipsis");
1797 INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
1798 INIT_TYPE(&_PyNamespace_Type, "namespace");
1799 INIT_TYPE(&PyCapsule_Type, "capsule");
1800 INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
1801 INIT_TYPE(&PyCell_Type, "cell");
1802 INIT_TYPE(&PyInstanceMethod_Type, "instance method");
1803 INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
1804 INIT_TYPE(&PyMethodDescr_Type, "method descr");
1805 INIT_TYPE(&PyCallIter_Type, "call iter");
1806 INIT_TYPE(&PySeqIter_Type, "sequence iterator");
1807 INIT_TYPE(&PyCoro_Type, "coroutine");
1808 INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
1809 return _Py_INIT_OK();
Guido van Rossumba21a492001-08-16 08:17:26 +00001810
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001811#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001812}
1813
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001814
Guido van Rossum84a90321996-05-22 16:34:47 +00001815#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001816
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001817void
Fred Drake100814d2000-07-09 15:48:49 +00001818_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001819{
Victor Stinner9e00e802018-10-25 13:31:16 +02001820 if (_Py_tracemalloc_config.tracing) {
1821 _PyTraceMalloc_NewReference(op);
1822 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 _Py_INC_REFTOTAL;
1824 op->ob_refcnt = 1;
1825 _Py_AddToAllObjects(op, 1);
1826 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001827}
1828
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001829void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001830_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001831{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001832#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001833 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001834#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 if (op->ob_refcnt < 0)
1836 Py_FatalError("UNREF negative refcnt");
1837 if (op == &refchain ||
1838 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1839 fprintf(stderr, "* ob\n");
1840 _PyObject_Dump(op);
1841 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1842 _PyObject_Dump(op->_ob_prev->_ob_next);
1843 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1844 _PyObject_Dump(op->_ob_next->_ob_prev);
1845 Py_FatalError("UNREF invalid object");
1846 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001847#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1849 if (p == op)
1850 break;
1851 }
1852 if (p == &refchain) /* Not found */
1853 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001854#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 op->_ob_next->_ob_prev = op->_ob_prev;
1856 op->_ob_prev->_ob_next = op->_ob_next;
1857 op->_ob_next = op->_ob_prev = NULL;
1858 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001859}
1860
Tim Peters269b2a62003-04-17 19:52:29 +00001861/* Print all live objects. Because PyObject_Print is called, the
1862 * interpreter must be in a healthy state.
1863 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001864void
Fred Drake100814d2000-07-09 15:48:49 +00001865_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 PyObject *op;
1868 fprintf(fp, "Remaining objects:\n");
1869 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1870 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1871 if (PyObject_Print(op, fp, 0) != 0)
1872 PyErr_Clear();
1873 putc('\n', fp);
1874 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001875}
1876
Tim Peters269b2a62003-04-17 19:52:29 +00001877/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1878 * doesn't make any calls to the Python C API, so is always safe to call.
1879 */
1880void
1881_Py_PrintReferenceAddresses(FILE *fp)
1882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 PyObject *op;
1884 fprintf(fp, "Remaining object addresses:\n");
1885 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1886 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1887 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001888}
1889
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001890PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001891_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 int i, n;
1894 PyObject *t = NULL;
1895 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1898 return NULL;
1899 op = refchain._ob_next;
1900 res = PyList_New(0);
1901 if (res == NULL)
1902 return NULL;
1903 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1904 while (op == self || op == args || op == res || op == t ||
1905 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1906 op = op->_ob_next;
1907 if (op == &refchain)
1908 return res;
1909 }
1910 if (PyList_Append(res, op) < 0) {
1911 Py_DECREF(res);
1912 return NULL;
1913 }
1914 op = op->_ob_next;
1915 }
1916 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001917}
1918
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001919#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001920
Benjamin Petersonb173f782009-05-05 22:31:58 +00001921
Guido van Rossum84a90321996-05-22 16:34:47 +00001922/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001923Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001924
1925
David Malcolm49526f42012-06-22 14:55:41 -04001926void
1927_PyObject_DebugTypeStats(FILE *out)
1928{
1929 _PyCFunction_DebugMallocStats(out);
1930 _PyDict_DebugMallocStats(out);
1931 _PyFloat_DebugMallocStats(out);
1932 _PyFrame_DebugMallocStats(out);
1933 _PyList_DebugMallocStats(out);
1934 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001935 _PyTuple_DebugMallocStats(out);
1936}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001937
Guido van Rossum86610361998-04-10 22:32:46 +00001938/* These methods are used to control infinite recursion in repr, str, print,
1939 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00001940 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00001941 Py_ReprLeave() to avoid infinite recursion.
1942
1943 Py_ReprEnter() returns 0 the first time it is called for a particular
1944 object and 1 every time thereafter. It returns -1 if an exception
1945 occurred. Py_ReprLeave() has no return value.
1946
1947 See dictobject.c and listobject.c for examples of use.
1948*/
1949
Guido van Rossum86610361998-04-10 22:32:46 +00001950int
Fred Drake100814d2000-07-09 15:48:49 +00001951Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 PyObject *dict;
1954 PyObject *list;
1955 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02001958 /* Ignore a missing thread-state, so that this function can be called
1959 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 if (dict == NULL)
1961 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001962 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001964 if (PyErr_Occurred()) {
1965 return -1;
1966 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 list = PyList_New(0);
1968 if (list == NULL)
1969 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001970 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 return -1;
1972 Py_DECREF(list);
1973 }
1974 i = PyList_GET_SIZE(list);
1975 while (--i >= 0) {
1976 if (PyList_GET_ITEM(list, i) == obj)
1977 return 1;
1978 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02001979 if (PyList_Append(list, obj) < 0)
1980 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001982}
1983
1984void
Fred Drake100814d2000-07-09 15:48:49 +00001985Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 PyObject *dict;
1988 PyObject *list;
1989 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02001990 PyObject *error_type, *error_value, *error_traceback;
1991
1992 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 dict = PyThreadState_GetDict();
1995 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02001996 goto finally;
1997
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001998 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002000 goto finally;
2001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 i = PyList_GET_SIZE(list);
2003 /* Count backwards because we always expect obj to be list[-1] */
2004 while (--i >= 0) {
2005 if (PyList_GET_ITEM(list, i) == obj) {
2006 PyList_SetSlice(list, i, i + 1, NULL);
2007 break;
2008 }
2009 }
Victor Stinner1b634932013-07-16 22:24:44 +02002010
2011finally:
2012 /* ignore exceptions because there is no way to report them. */
2013 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002014}
Guido van Rossumd724b232000-03-13 16:01:29 +00002015
Tim Peters803526b2002-07-07 05:13:56 +00002016/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002017
Tim Peters803526b2002-07-07 05:13:56 +00002018/* Add op to the _PyTrash_delete_later list. Called when the current
2019 * call-stack depth gets large. op must be a currently untracked gc'ed
2020 * object, with refcount 0. Py_DECREF must already have been called on it.
2021 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002022void
Fred Drake100814d2000-07-09 15:48:49 +00002023_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002024{
Victor Stinner24702042018-10-26 17:16:37 +02002025 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2026 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2027 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002028 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002029 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002030}
2031
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002032/* The equivalent API, using per-thread state recursion info */
2033void
2034_PyTrash_thread_deposit_object(PyObject *op)
2035{
Victor Stinner50b48572018-11-01 01:51:40 +01002036 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002037 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2038 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2039 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002040 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002041 tstate->trash_delete_later = op;
2042}
2043
Tim Peters803526b2002-07-07 05:13:56 +00002044/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2045 * the call-stack unwinds again.
2046 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002047void
Fred Drake100814d2000-07-09 15:48:49 +00002048_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002049{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002050 while (_PyRuntime.gc.trash_delete_later) {
2051 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002053
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002054 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002055 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 /* Call the deallocator directly. This used to try to
2058 * fool Py_DECREF into calling it indirectly, but
2059 * Py_DECREF was already called on this object, and in
2060 * assorted non-release builds calling Py_DECREF again ends
2061 * up distorting allocation statistics.
2062 */
Victor Stinner24702042018-10-26 17:16:37 +02002063 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002064 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002066 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002068}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002069
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002070/* The equivalent API, using per-thread state recursion info */
2071void
2072_PyTrash_thread_destroy_chain(void)
2073{
Victor Stinner50b48572018-11-01 01:51:40 +01002074 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002075 /* We need to increase trash_delete_nesting here, otherwise,
2076 _PyTrash_thread_destroy_chain will be called recursively
2077 and then possibly crash. An example that may crash without
2078 increase:
2079 N = 500000 # need to be large enough
2080 ob = object()
2081 tups = [(ob,) for i in range(N)]
2082 for i in range(49):
2083 tups = [(tup,) for tup in tups]
2084 del tups
2085 */
2086 assert(tstate->trash_delete_nesting == 0);
2087 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002088 while (tstate->trash_delete_later) {
2089 PyObject *op = tstate->trash_delete_later;
2090 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2091
2092 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002093 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002094
2095 /* Call the deallocator directly. This used to try to
2096 * fool Py_DECREF into calling it indirectly, but
2097 * Py_DECREF was already called on this object, and in
2098 * assorted non-release builds calling Py_DECREF again ends
2099 * up distorting allocation statistics.
2100 */
Victor Stinner24702042018-10-26 17:16:37 +02002101 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002102 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002103 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002104 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002105 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002106}
2107
Victor Stinner626bff82018-10-25 17:31:10 +02002108
2109void
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002110_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002111 const char *file, int line, const char *function)
2112{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002113 fprintf(stderr, "%s:%d: ", file, line);
2114 if (function) {
2115 fprintf(stderr, "%s: ", function);
2116 }
Victor Stinner626bff82018-10-25 17:31:10 +02002117 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002118 if (expr) {
2119 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002120 }
2121 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002122 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002123 }
2124 fflush(stderr);
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002125 if (msg) {
2126 fprintf(stderr, ": %s", msg);
2127 }
2128 fprintf(stderr, "\n");
2129 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002130
2131 if (obj == NULL) {
2132 fprintf(stderr, "<NULL object>\n");
2133 }
2134 else if (_PyObject_IsFreed(obj)) {
2135 /* It seems like the object memory has been freed:
2136 don't access it to prevent a segmentation fault. */
2137 fprintf(stderr, "<Freed object>\n");
2138 }
2139 else {
2140 /* Diplay the traceback where the object has been allocated.
2141 Do it before dumping repr(obj), since repr() is more likely
2142 to crash than dumping the traceback. */
2143 void *ptr;
2144 PyTypeObject *type = Py_TYPE(obj);
2145 if (PyType_IS_GC(type)) {
2146 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2147 }
2148 else {
2149 ptr = (void *)obj;
2150 }
2151 _PyMem_DumpTraceback(fileno(stderr), ptr);
2152
2153 /* This might succeed or fail, but we're about to abort, so at least
2154 try to provide any extra info we can: */
2155 _PyObject_Dump(obj);
2156 }
2157 fflush(stderr);
2158
2159 Py_FatalError("_PyObject_AssertFailed");
2160}
2161
Victor Stinner3c09dca2018-10-30 14:48:26 +01002162
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002163#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002164
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002165void
2166_Py_Dealloc(PyObject *op)
2167{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002168 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2169#ifdef Py_TRACE_REFS
2170 _Py_ForgetReference(op);
2171#else
2172 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002173#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002174 (*dealloc)(op);
2175}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002176
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002177#ifdef __cplusplus
2178}
2179#endif