blob: 2252f98347566f94f370f51139d745fb6fee93b9 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06005#include "internal/pystate.h"
Yury Selivanovf23746a2018-01-22 19:11:18 -05006#include "internal/context.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00007#include "frameobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009#ifdef __cplusplus
10extern "C" {
11#endif
12
Victor Stinner626bff82018-10-25 17:31:10 +020013/* Defined in tracemalloc.c */
14extern void _PyMem_DumpTraceback(int fd, const void *ptr);
15
Victor Stinnerbd303c12013-11-07 23:07:29 +010016_Py_IDENTIFIER(Py_Repr);
17_Py_IDENTIFIER(__bytes__);
18_Py_IDENTIFIER(__dir__);
19_Py_IDENTIFIER(__isabstractmethod__);
20_Py_IDENTIFIER(builtins);
21
Tim Peters34592512002-07-11 06:23:50 +000022#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000023Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000024
25Py_ssize_t
26_Py_GetRefTotal(void)
27{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 PyObject *o;
29 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020030 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 if (o != NULL)
32 total -= o->ob_refcnt;
33 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000034}
Nick Coghland6009512014-11-20 21:39:37 +100035
36void
37_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070038 fprintf(stderr,
39 "[%" PY_FORMAT_SIZE_T "d refs, "
40 "%" PY_FORMAT_SIZE_T "d blocks]\n",
41 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100042}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044
Guido van Rossum3f5da241990-12-20 15:06:42 +000045/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
46 These are used by the individual routines for object creation.
47 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000048
Tim Peters78be7992003-03-23 02:51:01 +000049#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000050/* Head of circular doubly-linked list of all objects. These are linked
51 * together via the _ob_prev and _ob_next members of a PyObject, which
52 * exist only in a Py_TRACE_REFS build.
53 */
Tim Peters78be7992003-03-23 02:51:01 +000054static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000055
Tim Peters7571a0f2003-03-23 17:52:28 +000056/* Insert op at the front of the list of all objects. If force is true,
57 * op is added even if _ob_prev and _ob_next are non-NULL already. If
58 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
59 * force should be true if and only if op points to freshly allocated,
60 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000061 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000062 * Note that objects are normally added to the list via _Py_NewReference,
63 * which is called by PyObject_Init. Not all objects are initialized that
64 * way, though; exceptions include statically allocated type objects, and
65 * statically allocated singletons (like Py_True and Py_None).
66 */
Tim Peters36eb4df2003-03-23 03:33:13 +000067void
Tim Peters7571a0f2003-03-23 17:52:28 +000068_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000069{
Tim Peters7571a0f2003-03-23 17:52:28 +000070#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 if (!force) {
72 /* If it's initialized memory, op must be in or out of
73 * the list unambiguously.
74 */
75 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
76 }
Tim Peters78be7992003-03-23 02:51:01 +000077#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (force || op->_ob_prev == NULL) {
79 op->_ob_next = refchain._ob_next;
80 op->_ob_prev = &refchain;
81 refchain._ob_next->_ob_prev = op;
82 refchain._ob_next = op;
83 }
Tim Peters7571a0f2003-03-23 17:52:28 +000084}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000086
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000087#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000088static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089/* All types are added to type_list, at least when
90 they get one object created. That makes them
91 immortal, which unfortunately contributes to
92 garbage itself. If unlist_types_without_objects
93 is set, they will be removed from the type_list
94 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +000095static int unlist_types_without_objects;
96extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
97extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
98extern Py_ssize_t null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000099void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000100dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000101{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200102 PyInterpreterState *interp = _PyInterpreterState_Get();
Eddie Elizondo745dc652018-02-21 20:55:18 -0800103 if (!interp->core_config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300104 return;
Victor Stinner25420fe2017-11-20 18:12:22 -0800105 }
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000106
Eddie Elizondo745dc652018-02-21 20:55:18 -0800107 PyTypeObject *tp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 for (tp = type_list; tp; tp = tp->tp_next)
109 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
110 "freed: %" PY_FORMAT_SIZE_T "d, "
111 "max in use: %" PY_FORMAT_SIZE_T "d\n",
112 tp->tp_name, tp->tp_allocs, tp->tp_frees,
113 tp->tp_maxalloc);
114 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
115 "empty: %" PY_FORMAT_SIZE_T "d\n",
116 fast_tuple_allocs, tuple_zero_allocs);
117 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
118 "neg: %" PY_FORMAT_SIZE_T "d\n",
119 quick_int_allocs, quick_neg_int_allocs);
120 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
121 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
122 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000123}
124
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000125PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000126get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyTypeObject *tp;
129 PyObject *result;
130 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 result = PyList_New(0);
133 if (result == NULL)
134 return NULL;
135 for (tp = type_list; tp; tp = tp->tp_next) {
136 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
137 tp->tp_frees, tp->tp_maxalloc);
138 if (v == NULL) {
139 Py_DECREF(result);
140 return NULL;
141 }
142 if (PyList_Append(result, v) < 0) {
143 Py_DECREF(v);
144 Py_DECREF(result);
145 return NULL;
146 }
147 Py_DECREF(v);
148 }
149 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000150}
151
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000152void
Fred Drake100814d2000-07-09 15:48:49 +0000153inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
156 /* first time; insert in linked list */
157 if (tp->tp_next != NULL) /* sanity check */
158 Py_FatalError("XXX inc_count sanity check");
159 if (type_list)
160 type_list->tp_prev = tp;
161 tp->tp_next = type_list;
162 /* Note that as of Python 2.2, heap-allocated type objects
163 * can go away, but this code requires that they stay alive
164 * until program exit. That's why we're careful with
165 * refcounts here. type_list gets a new reference to tp,
166 * while ownership of the reference type_list used to hold
167 * (if any) was transferred to tp->tp_next in the line above.
168 * tp is thus effectively immortal after this.
169 */
170 Py_INCREF(tp);
171 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000172#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 /* Also insert in the doubly-linked list of all objects,
174 * if not already there.
175 */
176 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
179 tp->tp_allocs++;
180 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
181 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000182}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000183
184void dec_count(PyTypeObject *tp)
185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 tp->tp_frees++;
187 if (unlist_types_without_objects &&
188 tp->tp_allocs == tp->tp_frees) {
189 /* unlink the type from type_list */
190 if (tp->tp_prev)
191 tp->tp_prev->tp_next = tp->tp_next;
192 else
193 type_list = tp->tp_next;
194 if (tp->tp_next)
195 tp->tp_next->tp_prev = tp->tp_prev;
196 tp->tp_next = tp->tp_prev = NULL;
197 Py_DECREF(tp);
198 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000199}
200
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000201#endif
202
Tim Peters7c321a82002-07-09 02:57:01 +0000203#ifdef Py_REF_DEBUG
204/* Log a fatal error; doesn't return. */
205void
Victor Stinner18618e652018-10-25 17:28:11 +0200206_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 PyOS_snprintf(buf, sizeof(buf),
211 "%s:%i object at %p has negative ref count "
212 "%" PY_FORMAT_SIZE_T "d",
Victor Stinner18618e652018-10-25 17:28:11 +0200213 filename, lineno, op, op->ob_refcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000215}
216
217#endif /* Py_REF_DEBUG */
218
Thomas Heller1328b522004-04-22 17:23:49 +0000219void
220Py_IncRef(PyObject *o)
221{
222 Py_XINCREF(o);
223}
224
225void
226Py_DecRef(PyObject *o)
227{
228 Py_XDECREF(o);
229}
230
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000231PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000232PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (op == NULL)
235 return PyErr_NoMemory();
236 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
237 Py_TYPE(op) = tp;
238 _Py_NewReference(op);
239 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240}
241
Guido van Rossumb18618d2000-05-03 23:44:39 +0000242PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000243PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (op == NULL)
246 return (PyVarObject *) PyErr_NoMemory();
247 /* Any changes should be reflected in PyObject_INIT_VAR */
248 op->ob_size = size;
249 Py_TYPE(op) = tp;
250 _Py_NewReference((PyObject *)op);
251 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000252}
253
254PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000255_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 PyObject *op;
258 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
259 if (op == NULL)
260 return PyErr_NoMemory();
261 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000262}
263
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000264PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000265_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 PyVarObject *op;
268 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
269 op = (PyVarObject *) PyObject_MALLOC(size);
270 if (op == NULL)
271 return (PyVarObject *)PyErr_NoMemory();
272 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000273}
274
Antoine Pitrou796564c2013-07-30 19:59:21 +0200275void
276PyObject_CallFinalizer(PyObject *self)
277{
278 PyTypeObject *tp = Py_TYPE(self);
279
280 /* The former could happen on heaptypes created from the C API, e.g.
281 PyType_FromSpec(). */
282 if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
283 tp->tp_finalize == NULL)
284 return;
285 /* tp_finalize should only be called once. */
286 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
287 return;
288
289 tp->tp_finalize(self);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900290 if (PyType_IS_GC(tp)) {
291 _PyGC_SET_FINALIZED(self);
292 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200293}
294
295int
296PyObject_CallFinalizerFromDealloc(PyObject *self)
297{
298 Py_ssize_t refcnt;
299
300 /* Temporarily resurrect the object. */
301 if (self->ob_refcnt != 0) {
302 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
303 "object with a non-zero refcount");
304 }
305 self->ob_refcnt = 1;
306
307 PyObject_CallFinalizer(self);
308
309 /* Undo the temporary resurrection; can't use DECREF here, it would
310 * cause a recursive call.
311 */
312 assert(self->ob_refcnt > 0);
313 if (--self->ob_refcnt == 0)
314 return 0; /* this is the normal path out */
315
316 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
317 * never happened.
318 */
319 refcnt = self->ob_refcnt;
320 _Py_NewReference(self);
321 self->ob_refcnt = refcnt;
322
INADA Naokid8521422018-05-17 11:07:21 +0900323 assert(!PyType_IS_GC(Py_TYPE(self)) || _PyObject_GC_IS_TRACKED(self));
Antoine Pitrou796564c2013-07-30 19:59:21 +0200324 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
325 * we need to undo that. */
326 _Py_DEC_REFTOTAL;
327 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
328 * chain, so no more to do there.
329 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
330 * _Py_NewReference bumped tp_allocs: both of those need to be
331 * undone.
332 */
333#ifdef COUNT_ALLOCS
334 --Py_TYPE(self)->tp_frees;
335 --Py_TYPE(self)->tp_allocs;
336#endif
337 return -1;
338}
339
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000340int
341PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (PyErr_CheckSignals())
345 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000346#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (PyOS_CheckStack()) {
348 PyErr_SetString(PyExc_MemoryError, "stack overflow");
349 return -1;
350 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000351#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 clearerr(fp); /* Clear any previous error condition */
353 if (op == NULL) {
354 Py_BEGIN_ALLOW_THREADS
355 fprintf(fp, "<nil>");
356 Py_END_ALLOW_THREADS
357 }
358 else {
359 if (op->ob_refcnt <= 0)
360 /* XXX(twouters) cast refcount to long until %zd is
361 universally available */
362 Py_BEGIN_ALLOW_THREADS
363 fprintf(fp, "<refcnt %ld at %p>",
364 (long)op->ob_refcnt, op);
365 Py_END_ALLOW_THREADS
366 else {
367 PyObject *s;
368 if (flags & Py_PRINT_RAW)
369 s = PyObject_Str(op);
370 else
371 s = PyObject_Repr(op);
372 if (s == NULL)
373 ret = -1;
374 else if (PyBytes_Check(s)) {
375 fwrite(PyBytes_AS_STRING(s), 1,
376 PyBytes_GET_SIZE(s), fp);
377 }
378 else if (PyUnicode_Check(s)) {
379 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200380 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600381 if (t == NULL) {
382 ret = -1;
383 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 else {
385 fwrite(PyBytes_AS_STRING(t), 1,
386 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000387 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 }
389 }
390 else {
391 PyErr_Format(PyExc_TypeError,
392 "str() or repr() returned '%.100s'",
393 s->ob_type->tp_name);
394 ret = -1;
395 }
396 Py_XDECREF(s);
397 }
398 }
399 if (ret == 0) {
400 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300401 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 clearerr(fp);
403 ret = -1;
404 }
405 }
406 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407}
408
Guido van Rossum38938152006-08-21 23:36:26 +0000409/* For debugging convenience. Set a breakpoint here and call it from your DLL */
410void
Thomas Woutersb2137042007-02-01 18:02:27 +0000411_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000412{
413}
414
Neal Norwitz1a997502003-01-13 20:13:12 +0000415
Victor Stinner82af0b62018-10-23 17:39:40 +0200416/* Heuristic checking if the object memory has been deallocated.
417 Rely on the debug hooks on Python memory allocators which fills the memory
418 with DEADBYTE (0xDB) when memory is deallocated.
419
420 The function can be used to prevent segmentation fault on dereferencing
421 pointers like 0xdbdbdbdbdbdbdbdb. Such pointer is very unlikely to be mapped
422 in memory. */
423int
424_PyObject_IsFreed(PyObject *op)
425{
426 int freed = _PyMem_IsFreed(&op->ob_type, sizeof(op->ob_type));
427 /* ignore op->ob_ref: the value can have be modified
428 by Py_INCREF() and Py_DECREF(). */
429#ifdef Py_TRACE_REFS
430 freed &= _PyMem_IsFreed(&op->_ob_next, sizeof(op->_ob_next));
431 freed &= _PyMem_IsFreed(&op->_ob_prev, sizeof(op->_ob_prev));
432#endif
433 return freed;
434}
435
436
Barry Warsaw9bf16442001-01-23 16:24:35 +0000437/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000438void
439_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000440{
Victor Stinner82af0b62018-10-23 17:39:40 +0200441 if (op == NULL) {
442 fprintf(stderr, "<NULL object>\n");
443 fflush(stderr);
444 return;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200446
447 if (_PyObject_IsFreed(op)) {
448 /* It seems like the object memory has been freed:
449 don't access it to prevent a segmentation fault. */
450 fprintf(stderr, "<freed object>\n");
451 }
452
453 PyGILState_STATE gil;
454 PyObject *error_type, *error_value, *error_traceback;
455
456 fprintf(stderr, "object : ");
457 fflush(stderr);
458 gil = PyGILState_Ensure();
459
460 PyErr_Fetch(&error_type, &error_value, &error_traceback);
461 (void)PyObject_Print(op, stderr, 0);
462 fflush(stderr);
463 PyErr_Restore(error_type, error_value, error_traceback);
464
465 PyGILState_Release(gil);
466 /* XXX(twouters) cast refcount to long until %zd is
467 universally available */
468 fprintf(stderr, "\n"
469 "type : %s\n"
470 "refcount: %ld\n"
471 "address : %p\n",
472 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
473 (long)op->ob_refcnt,
474 op);
475 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000476}
Barry Warsaw903138f2001-01-23 16:33:18 +0000477
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000479PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 PyObject *res;
482 if (PyErr_CheckSignals())
483 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000484#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 if (PyOS_CheckStack()) {
486 PyErr_SetString(PyExc_MemoryError, "stack overflow");
487 return NULL;
488 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000489#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (v == NULL)
491 return PyUnicode_FromString("<NULL>");
492 if (Py_TYPE(v)->tp_repr == NULL)
493 return PyUnicode_FromFormat("<%s object at %p>",
494 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200495
496#ifdef Py_DEBUG
497 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100498 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000499 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200500 assert(!PyErr_Occurred());
501#endif
502
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200503 /* It is possible for a type to have a tp_repr representation that loops
504 infinitely. */
505 if (Py_EnterRecursiveCall(" while getting the repr of an object"))
506 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 res = (*v->ob_type->tp_repr)(v);
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200508 Py_LeaveRecursiveCall();
Victor Stinner0a54cf12011-12-01 03:22:44 +0100509 if (res == NULL)
510 return NULL;
511 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyErr_Format(PyExc_TypeError,
513 "__repr__ returned non-string (type %.200s)",
514 res->ob_type->tp_name);
515 Py_DECREF(res);
516 return NULL;
517 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100518#ifndef Py_DEBUG
519 if (PyUnicode_READY(res) < 0)
520 return NULL;
521#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523}
524
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000525PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000526PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 PyObject *res;
529 if (PyErr_CheckSignals())
530 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000531#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (PyOS_CheckStack()) {
533 PyErr_SetString(PyExc_MemoryError, "stack overflow");
534 return NULL;
535 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000536#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (v == NULL)
538 return PyUnicode_FromString("<NULL>");
539 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100540#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100541 if (PyUnicode_READY(v) < 0)
542 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100543#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 Py_INCREF(v);
545 return v;
546 }
547 if (Py_TYPE(v)->tp_str == NULL)
548 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000549
Victor Stinner33824f62013-08-26 14:05:19 +0200550#ifdef Py_DEBUG
551 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100552 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000553 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200554 assert(!PyErr_Occurred());
555#endif
556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 /* It is possible for a type to have a tp_str representation that loops
558 infinitely. */
559 if (Py_EnterRecursiveCall(" while getting the str of an object"))
560 return NULL;
561 res = (*Py_TYPE(v)->tp_str)(v);
562 Py_LeaveRecursiveCall();
563 if (res == NULL)
564 return NULL;
565 if (!PyUnicode_Check(res)) {
566 PyErr_Format(PyExc_TypeError,
567 "__str__ returned non-string (type %.200s)",
568 Py_TYPE(res)->tp_name);
569 Py_DECREF(res);
570 return NULL;
571 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100572#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100573 if (PyUnicode_READY(res) < 0)
574 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100575#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100576 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000578}
579
Georg Brandl559e5d72008-06-11 18:37:52 +0000580PyObject *
581PyObject_ASCII(PyObject *v)
582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 repr = PyObject_Repr(v);
586 if (repr == NULL)
587 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000588
Victor Stinneraf037572013-04-14 18:44:10 +0200589 if (PyUnicode_IS_ASCII(repr))
590 return repr;
591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200593 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 Py_DECREF(repr);
595 if (ascii == NULL)
596 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 res = PyUnicode_DecodeASCII(
599 PyBytes_AS_STRING(ascii),
600 PyBytes_GET_SIZE(ascii),
601 NULL);
602
603 Py_DECREF(ascii);
604 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000605}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000606
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000607PyObject *
608PyObject_Bytes(PyObject *v)
609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (v == NULL)
613 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (PyBytes_CheckExact(v)) {
616 Py_INCREF(v);
617 return v;
618 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000619
Benjamin Petersonce798522012-01-22 11:24:29 -0500620 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100622 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 Py_DECREF(func);
624 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000625 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000627 PyErr_Format(PyExc_TypeError,
628 "__bytes__ returned non-bytes (type %.200s)",
629 Py_TYPE(result)->tp_name);
630 Py_DECREF(result);
631 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 }
633 return result;
634 }
635 else if (PyErr_Occurred())
636 return NULL;
637 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000638}
639
Mark Dickinsonc008a172009-02-01 13:59:22 +0000640/* For Python 3.0.1 and later, the old three-way comparison has been
641 completely removed in favour of rich comparisons. PyObject_Compare() and
642 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000643 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000644 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000645
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000646 See (*) below for practical amendments.
647
Mark Dickinsonc008a172009-02-01 13:59:22 +0000648 tp_richcompare gets called with a first argument of the appropriate type
649 and a second object of an arbitrary type. We never do any kind of
650 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000651
Mark Dickinsonc008a172009-02-01 13:59:22 +0000652 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000653
654 NULL if an exception occurred
655 NotImplemented if the requested comparison is not implemented
656 any other false value if the requested comparison is false
657 any other true value if the requested comparison is true
658
659 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
660 NotImplemented.
661
662 (*) Practical amendments:
663
664 - If rich comparison returns NotImplemented, == and != are decided by
665 comparing the object pointer (i.e. falling back to the base object
666 implementation).
667
Guido van Rossuma4073002002-05-31 20:03:54 +0000668*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000669
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000670/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000671int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000672
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200673static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000674
675/* Perform a rich comparison, raising TypeError when the requested comparison
676 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000677static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000678do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 richcmpfunc f;
681 PyObject *res;
682 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (v->ob_type != w->ob_type &&
685 PyType_IsSubtype(w->ob_type, v->ob_type) &&
686 (f = w->ob_type->tp_richcompare) != NULL) {
687 checked_reverse_op = 1;
688 res = (*f)(w, v, _Py_SwappedOp[op]);
689 if (res != Py_NotImplemented)
690 return res;
691 Py_DECREF(res);
692 }
693 if ((f = v->ob_type->tp_richcompare) != NULL) {
694 res = (*f)(v, w, op);
695 if (res != Py_NotImplemented)
696 return res;
697 Py_DECREF(res);
698 }
699 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
700 res = (*f)(w, v, _Py_SwappedOp[op]);
701 if (res != Py_NotImplemented)
702 return res;
703 Py_DECREF(res);
704 }
705 /* If neither object implements it, provide a sensible default
706 for == and !=, but raise an exception for ordering. */
707 switch (op) {
708 case Py_EQ:
709 res = (v == w) ? Py_True : Py_False;
710 break;
711 case Py_NE:
712 res = (v != w) ? Py_True : Py_False;
713 break;
714 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyErr_Format(PyExc_TypeError,
Victor Stinner91108f02015-10-14 18:25:31 +0200716 "'%s' not supported between instances of '%.100s' and '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 opstrings[op],
Victor Stinner91108f02015-10-14 18:25:31 +0200718 v->ob_type->tp_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 w->ob_type->tp_name);
720 return NULL;
721 }
722 Py_INCREF(res);
723 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000724}
725
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000726/* Perform a rich comparison with object result. This wraps do_richcompare()
727 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000728
Guido van Rossume797ec12001-01-17 15:24:28 +0000729PyObject *
730PyObject_RichCompare(PyObject *v, PyObject *w, int op)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 assert(Py_LT <= op && op <= Py_GE);
735 if (v == NULL || w == NULL) {
736 if (!PyErr_Occurred())
737 PyErr_BadInternalCall();
738 return NULL;
739 }
740 if (Py_EnterRecursiveCall(" in comparison"))
741 return NULL;
742 res = do_richcompare(v, w, op);
743 Py_LeaveRecursiveCall();
744 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000745}
746
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000747/* Perform a rich comparison with integer result. This wraps
748 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000749int
750PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyObject *res;
753 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 /* Quick result when objects are the same.
756 Guarantees that identity implies equality. */
757 if (v == w) {
758 if (op == Py_EQ)
759 return 1;
760 else if (op == Py_NE)
761 return 0;
762 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 res = PyObject_RichCompare(v, w, op);
765 if (res == NULL)
766 return -1;
767 if (PyBool_Check(res))
768 ok = (res == Py_True);
769 else
770 ok = PyObject_IsTrue(res);
771 Py_DECREF(res);
772 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000773}
Fred Drake13634cf2000-06-29 19:17:04 +0000774
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100775Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000776PyObject_HashNotImplemented(PyObject *v)
777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
779 Py_TYPE(v)->tp_name);
780 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000781}
Fred Drake13634cf2000-06-29 19:17:04 +0000782
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000783Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000784PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyTypeObject *tp = Py_TYPE(v);
787 if (tp->tp_hash != NULL)
788 return (*tp->tp_hash)(v);
789 /* To keep to the general practice that inheriting
790 * solely from object in C code should work without
791 * an explicit call to PyType_Ready, we implicitly call
792 * PyType_Ready here and then check the tp_hash slot again
793 */
794 if (tp->tp_dict == NULL) {
795 if (PyType_Ready(tp) < 0)
796 return -1;
797 if (tp->tp_hash != NULL)
798 return (*tp->tp_hash)(v);
799 }
800 /* Otherwise, the object can't be hashed */
801 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000802}
803
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000805PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (Py_TYPE(v)->tp_getattr != NULL)
810 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900811 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (w == NULL)
813 return NULL;
814 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100815 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000817}
818
819int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000820PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 PyObject *res = PyObject_GetAttrString(v, name);
823 if (res != NULL) {
824 Py_DECREF(res);
825 return 1;
826 }
827 PyErr_Clear();
828 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000829}
830
831int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000832PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject *s;
835 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (Py_TYPE(v)->tp_setattr != NULL)
838 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
839 s = PyUnicode_InternFromString(name);
840 if (s == NULL)
841 return -1;
842 res = PyObject_SetAttr(v, s, w);
843 Py_XDECREF(s);
844 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000845}
846
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500847int
848_PyObject_IsAbstract(PyObject *obj)
849{
850 int res;
851 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500852
853 if (obj == NULL)
854 return 0;
855
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200856 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
857 if (res > 0) {
858 res = PyObject_IsTrue(isabstract);
859 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500860 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500861 return res;
862}
863
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000864PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200865_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
866{
867 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100868 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200869 if (!oname)
870 return NULL;
871 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200872 return result;
873}
874
875int
876_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
877{
878 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100879 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200880 if (!oname)
881 return -1;
882 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200883 return result;
884}
885
886int
887_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
888{
889 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100890 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200891 if (!oname)
892 return -1;
893 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200894 return result;
895}
896
897PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000898PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (!PyUnicode_Check(name)) {
903 PyErr_Format(PyExc_TypeError,
904 "attribute name must be string, not '%.200s'",
905 name->ob_type->tp_name);
906 return NULL;
907 }
908 if (tp->tp_getattro != NULL)
909 return (*tp->tp_getattro)(v, name);
910 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200911 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (name_str == NULL)
913 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200914 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 }
916 PyErr_Format(PyExc_AttributeError,
917 "'%.50s' object has no attribute '%U'",
918 tp->tp_name, name);
919 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000920}
921
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200922int
923_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900924{
925 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900926
927 if (!PyUnicode_Check(name)) {
928 PyErr_Format(PyExc_TypeError,
929 "attribute name must be string, not '%.200s'",
930 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200931 *result = NULL;
932 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900933 }
934
935 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200936 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
937 if (*result != NULL) {
938 return 1;
939 }
940 if (PyErr_Occurred()) {
941 return -1;
942 }
943 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900944 }
945 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200946 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900947 }
948 else if (tp->tp_getattr != NULL) {
949 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200950 if (name_str == NULL) {
951 *result = NULL;
952 return -1;
953 }
954 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900955 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900956 else {
957 *result = NULL;
958 return 0;
959 }
960
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200961 if (*result != NULL) {
962 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900963 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200964 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
965 return -1;
966 }
967 PyErr_Clear();
968 return 0;
969}
970
971int
972_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
973{
974 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
975 if (!oname) {
976 *result = NULL;
977 return -1;
978 }
979 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +0900980}
981
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000982int
Fred Drake100814d2000-07-09 15:48:49 +0000983PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000984{
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200985 PyObject *res;
986 if (_PyObject_LookupAttr(v, name, &res) < 0) {
987 PyErr_Clear();
988 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200990 if (res == NULL) {
991 return 0;
992 }
993 Py_DECREF(res);
994 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000995}
996
997int
Fred Drake100814d2000-07-09 15:48:49 +0000998PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyTypeObject *tp = Py_TYPE(v);
1001 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (!PyUnicode_Check(name)) {
1004 PyErr_Format(PyExc_TypeError,
1005 "attribute name must be string, not '%.200s'",
1006 name->ob_type->tp_name);
1007 return -1;
1008 }
1009 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyUnicode_InternInPlace(&name);
1012 if (tp->tp_setattro != NULL) {
1013 err = (*tp->tp_setattro)(v, name, value);
1014 Py_DECREF(name);
1015 return err;
1016 }
1017 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001018 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if (name_str == NULL)
1020 return -1;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001021 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 Py_DECREF(name);
1023 return err;
1024 }
1025 Py_DECREF(name);
1026 assert(name->ob_refcnt >= 1);
1027 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1028 PyErr_Format(PyExc_TypeError,
1029 "'%.100s' object has no attributes "
1030 "(%s .%U)",
1031 tp->tp_name,
1032 value==NULL ? "del" : "assign to",
1033 name);
1034 else
1035 PyErr_Format(PyExc_TypeError,
1036 "'%.100s' object has only read-only attributes "
1037 "(%s .%U)",
1038 tp->tp_name,
1039 value==NULL ? "del" : "assign to",
1040 name);
1041 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042}
1043
1044/* Helper to get a pointer to an object's __dict__ slot, if any */
1045
1046PyObject **
1047_PyObject_GetDictPtr(PyObject *obj)
1048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 Py_ssize_t dictoffset;
1050 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 dictoffset = tp->tp_dictoffset;
1053 if (dictoffset == 0)
1054 return NULL;
1055 if (dictoffset < 0) {
1056 Py_ssize_t tsize;
1057 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 tsize = ((PyVarObject *)obj)->ob_size;
1060 if (tsize < 0)
1061 tsize = -tsize;
1062 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 dictoffset += (long)size;
1065 assert(dictoffset > 0);
1066 assert(dictoffset % SIZEOF_VOID_P == 0);
1067 }
1068 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069}
1070
Tim Peters6d6c1a32001-08-02 04:15:00 +00001071PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001072PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 Py_INCREF(obj);
1075 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001076}
1077
Antoine Pitroua7013882012-04-05 00:04:20 +02001078/* Convenience function to get a builtin from its name */
1079PyObject *
1080_PyObject_GetBuiltin(const char *name)
1081{
Victor Stinner53e9ec42013-11-07 00:43:05 +01001082 PyObject *mod_name, *mod, *attr;
1083
Victor Stinnerbd303c12013-11-07 23:07:29 +01001084 mod_name = _PyUnicode_FromId(&PyId_builtins); /* borrowed */
Victor Stinner53e9ec42013-11-07 00:43:05 +01001085 if (mod_name == NULL)
1086 return NULL;
1087 mod = PyImport_Import(mod_name);
Antoine Pitroua7013882012-04-05 00:04:20 +02001088 if (mod == NULL)
1089 return NULL;
1090 attr = PyObject_GetAttrString(mod, name);
1091 Py_DECREF(mod);
1092 return attr;
1093}
1094
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001095/* Helper used when the __next__ method is removed from a type:
1096 tp_iternext is never NULL and can be safely called without checking
1097 on every iteration.
1098 */
1099
1100PyObject *
1101_PyObject_NextNotImplemented(PyObject *self)
1102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 PyErr_Format(PyExc_TypeError,
1104 "'%.200s' object is not iterable",
1105 Py_TYPE(self)->tp_name);
1106 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001107}
1108
Yury Selivanovf2392132016-12-13 19:03:51 -05001109
1110/* Specialized version of _PyObject_GenericGetAttrWithDict
1111 specifically for the LOAD_METHOD opcode.
1112
1113 Return 1 if a method is found, 0 if it's a regular attribute
1114 from __dict__ or something returned by using a descriptor
1115 protocol.
1116
1117 `method` will point to the resolved attribute or NULL. In the
1118 latter case, an error will be set.
1119*/
1120int
1121_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1122{
1123 PyTypeObject *tp = Py_TYPE(obj);
1124 PyObject *descr;
1125 descrgetfunc f = NULL;
1126 PyObject **dictptr, *dict;
1127 PyObject *attr;
1128 int meth_found = 0;
1129
1130 assert(*method == NULL);
1131
1132 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1133 || !PyUnicode_Check(name)) {
1134 *method = PyObject_GetAttr(obj, name);
1135 return 0;
1136 }
1137
1138 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1139 return 0;
1140
1141 descr = _PyType_Lookup(tp, name);
1142 if (descr != NULL) {
1143 Py_INCREF(descr);
INADA Naoki5566bbb2017-02-03 07:43:03 +09001144 if (PyFunction_Check(descr) ||
1145 (Py_TYPE(descr) == &PyMethodDescr_Type)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001146 meth_found = 1;
1147 } else {
1148 f = descr->ob_type->tp_descr_get;
1149 if (f != NULL && PyDescr_IsData(descr)) {
1150 *method = f(descr, obj, (PyObject *)obj->ob_type);
1151 Py_DECREF(descr);
1152 return 0;
1153 }
1154 }
1155 }
1156
1157 dictptr = _PyObject_GetDictPtr(obj);
1158 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1159 Py_INCREF(dict);
1160 attr = PyDict_GetItem(dict, name);
1161 if (attr != NULL) {
1162 Py_INCREF(attr);
1163 *method = attr;
1164 Py_DECREF(dict);
1165 Py_XDECREF(descr);
1166 return 0;
1167 }
1168 Py_DECREF(dict);
1169 }
1170
1171 if (meth_found) {
1172 *method = descr;
1173 return 1;
1174 }
1175
1176 if (f != NULL) {
1177 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1178 Py_DECREF(descr);
1179 return 0;
1180 }
1181
1182 if (descr != NULL) {
1183 *method = descr;
1184 return 0;
1185 }
1186
1187 PyErr_Format(PyExc_AttributeError,
1188 "'%.50s' object has no attribute '%U'",
1189 tp->tp_name, name);
1190 return 0;
1191}
1192
1193/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001194
Raymond Hettinger01538262003-03-17 08:24:35 +00001195PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001196_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1197 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001198{
Yury Selivanovf2392132016-12-13 19:03:51 -05001199 /* Make sure the logic of _PyObject_GetMethod is in sync with
1200 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001201
1202 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001203 */
1204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 PyTypeObject *tp = Py_TYPE(obj);
1206 PyObject *descr = NULL;
1207 PyObject *res = NULL;
1208 descrgetfunc f;
1209 Py_ssize_t dictoffset;
1210 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 if (!PyUnicode_Check(name)){
1213 PyErr_Format(PyExc_TypeError,
1214 "attribute name must be string, not '%.200s'",
1215 name->ob_type->tp_name);
1216 return NULL;
1217 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001218 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (tp->tp_dict == NULL) {
1221 if (PyType_Ready(tp) < 0)
1222 goto done;
1223 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 f = NULL;
1228 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001229 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 f = descr->ob_type->tp_descr_get;
1231 if (f != NULL && PyDescr_IsData(descr)) {
1232 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001233 if (res == NULL && suppress &&
1234 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1235 PyErr_Clear();
1236 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 goto done;
1238 }
1239 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001240
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001241 if (dict == NULL) {
1242 /* Inline _PyObject_GetDictPtr */
1243 dictoffset = tp->tp_dictoffset;
1244 if (dictoffset != 0) {
1245 if (dictoffset < 0) {
1246 Py_ssize_t tsize;
1247 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001248
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001249 tsize = ((PyVarObject *)obj)->ob_size;
1250 if (tsize < 0)
1251 tsize = -tsize;
1252 size = _PyObject_VAR_SIZE(tp, tsize);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001253 assert(size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001254
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001255 dictoffset += (Py_ssize_t)size;
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001256 assert(dictoffset > 0);
1257 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001259 dictptr = (PyObject **) ((char *)obj + dictoffset);
1260 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 }
1262 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001263 if (dict != NULL) {
1264 Py_INCREF(dict);
1265 res = PyDict_GetItem(dict, name);
1266 if (res != NULL) {
1267 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001268 Py_DECREF(dict);
1269 goto done;
1270 }
1271 Py_DECREF(dict);
1272 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (f != NULL) {
1275 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001276 if (res == NULL && suppress &&
1277 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1278 PyErr_Clear();
1279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 goto done;
1281 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (descr != NULL) {
1284 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001285 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 goto done;
1287 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001288
INADA Naoki378edee2018-01-16 20:52:41 +09001289 if (!suppress) {
1290 PyErr_Format(PyExc_AttributeError,
1291 "'%.50s' object has no attribute '%U'",
1292 tp->tp_name, name);
1293 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001294 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001295 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 Py_DECREF(name);
1297 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298}
1299
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001300PyObject *
1301PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1302{
INADA Naoki378edee2018-01-16 20:52:41 +09001303 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001304}
1305
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001307_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1308 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 PyTypeObject *tp = Py_TYPE(obj);
1311 PyObject *descr;
1312 descrsetfunc f;
1313 PyObject **dictptr;
1314 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (!PyUnicode_Check(name)){
1317 PyErr_Format(PyExc_TypeError,
1318 "attribute name must be string, not '%.200s'",
1319 name->ob_type->tp_name);
1320 return -1;
1321 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001323 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1324 return -1;
1325
1326 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001331 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001333 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 res = f(descr, obj, value);
1335 goto done;
1336 }
1337 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001339 if (dict == NULL) {
1340 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001341 if (dictptr == NULL) {
1342 if (descr == NULL) {
1343 PyErr_Format(PyExc_AttributeError,
1344 "'%.100s' object has no attribute '%U'",
1345 tp->tp_name, name);
1346 }
1347 else {
1348 PyErr_Format(PyExc_AttributeError,
1349 "'%.50s' object attribute '%U' is read-only",
1350 tp->tp_name, name);
1351 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001352 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001354 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001355 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001356 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001357 Py_INCREF(dict);
1358 if (value == NULL)
1359 res = PyDict_DelItem(dict, name);
1360 else
1361 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001362 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001364 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1365 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001366
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001367 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001368 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 Py_DECREF(name);
1370 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001371}
1372
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001373int
1374PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1375{
1376 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1377}
1378
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001379int
1380PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1381{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001382 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001383 if (dictptr == NULL) {
1384 PyErr_SetString(PyExc_AttributeError,
1385 "This object has no __dict__");
1386 return -1;
1387 }
1388 if (value == NULL) {
1389 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1390 return -1;
1391 }
1392 if (!PyDict_Check(value)) {
1393 PyErr_Format(PyExc_TypeError,
1394 "__dict__ must be set to a dictionary, "
1395 "not a '%.200s'", Py_TYPE(value)->tp_name);
1396 return -1;
1397 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001398 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001399 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001400 return 0;
1401}
1402
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001403
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001404/* Test a value used as condition, e.g., in a for or if statement.
1405 Return -1 if an error occurred */
1406
1407int
Fred Drake100814d2000-07-09 15:48:49 +00001408PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 Py_ssize_t res;
1411 if (v == Py_True)
1412 return 1;
1413 if (v == Py_False)
1414 return 0;
1415 if (v == Py_None)
1416 return 0;
1417 else if (v->ob_type->tp_as_number != NULL &&
1418 v->ob_type->tp_as_number->nb_bool != NULL)
1419 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1420 else if (v->ob_type->tp_as_mapping != NULL &&
1421 v->ob_type->tp_as_mapping->mp_length != NULL)
1422 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1423 else if (v->ob_type->tp_as_sequence != NULL &&
1424 v->ob_type->tp_as_sequence->sq_length != NULL)
1425 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1426 else
1427 return 1;
1428 /* if it is negative, it should be either -1 or -2 */
1429 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001430}
1431
Tim Peters803526b2002-07-07 05:13:56 +00001432/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001433 Return -1 if an error occurred */
1434
1435int
Fred Drake100814d2000-07-09 15:48:49 +00001436PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 int res;
1439 res = PyObject_IsTrue(v);
1440 if (res < 0)
1441 return res;
1442 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001443}
1444
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001445/* Test whether an object can be called */
1446
1447int
Fred Drake100814d2000-07-09 15:48:49 +00001448PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (x == NULL)
1451 return 0;
1452 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001453}
1454
Tim Peters7eea37e2001-09-04 22:08:56 +00001455
Georg Brandle32b4222007-03-10 22:13:27 +00001456/* Helper for PyObject_Dir without arguments: returns the local scope. */
1457static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001458_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001461 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001462
Victor Stinner41bb43a2013-10-29 01:19:37 +01001463 locals = PyEval_GetLocals();
1464 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 names = PyMapping_Keys(locals);
1468 if (!names)
1469 return NULL;
1470 if (!PyList_Check(names)) {
1471 PyErr_Format(PyExc_TypeError,
1472 "dir(): expected keys() of locals to be a list, "
1473 "not '%.200s'", Py_TYPE(names)->tp_name);
1474 Py_DECREF(names);
1475 return NULL;
1476 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001477 if (PyList_Sort(names)) {
1478 Py_DECREF(names);
1479 return NULL;
1480 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 /* the locals don't need to be DECREF'd */
1482 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001483}
1484
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001485/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001486static PyObject *
1487_dir_object(PyObject *obj)
1488{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001489 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001490 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 assert(obj);
1493 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001494 if (!PyErr_Occurred())
1495 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1496 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001498 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001499 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001500 Py_DECREF(dirfunc);
1501 if (result == NULL)
1502 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001503 /* return sorted(result) */
1504 sorted = PySequence_List(result);
1505 Py_DECREF(result);
1506 if (sorted == NULL)
1507 return NULL;
1508 if (PyList_Sort(sorted)) {
1509 Py_DECREF(sorted);
1510 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001512 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001513}
1514
1515/* Implementation of dir() -- if obj is NULL, returns the names in the current
1516 (local) scope. Otherwise, performs introspection of the object: returns a
1517 sorted list of attribute names (supposedly) accessible from the object
1518*/
1519PyObject *
1520PyObject_Dir(PyObject *obj)
1521{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001522 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001523}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001524
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001525/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001526None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001527There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001528so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001529*/
1530
Guido van Rossum0c182a11992-03-27 17:26:13 +00001531/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001532static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001533none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001536}
1537
Barry Warsaw9bf16442001-01-23 16:24:35 +00001538/* ARGUSED */
1539static void
Tim Peters803526b2002-07-07 05:13:56 +00001540none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 /* This should never get called, but we also don't want to SEGV if
1543 * we accidentally decref None out of existence.
1544 */
1545 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001546}
1547
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001548static PyObject *
1549none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1550{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001551 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001552 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1553 return NULL;
1554 }
1555 Py_RETURN_NONE;
1556}
1557
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001558static int
1559none_bool(PyObject *v)
1560{
1561 return 0;
1562}
1563
1564static PyNumberMethods none_as_number = {
1565 0, /* nb_add */
1566 0, /* nb_subtract */
1567 0, /* nb_multiply */
1568 0, /* nb_remainder */
1569 0, /* nb_divmod */
1570 0, /* nb_power */
1571 0, /* nb_negative */
1572 0, /* nb_positive */
1573 0, /* nb_absolute */
1574 (inquiry)none_bool, /* nb_bool */
1575 0, /* nb_invert */
1576 0, /* nb_lshift */
1577 0, /* nb_rshift */
1578 0, /* nb_and */
1579 0, /* nb_xor */
1580 0, /* nb_or */
1581 0, /* nb_int */
1582 0, /* nb_reserved */
1583 0, /* nb_float */
1584 0, /* nb_inplace_add */
1585 0, /* nb_inplace_subtract */
1586 0, /* nb_inplace_multiply */
1587 0, /* nb_inplace_remainder */
1588 0, /* nb_inplace_power */
1589 0, /* nb_inplace_lshift */
1590 0, /* nb_inplace_rshift */
1591 0, /* nb_inplace_and */
1592 0, /* nb_inplace_xor */
1593 0, /* nb_inplace_or */
1594 0, /* nb_floor_divide */
1595 0, /* nb_true_divide */
1596 0, /* nb_inplace_floor_divide */
1597 0, /* nb_inplace_true_divide */
1598 0, /* nb_index */
1599};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001600
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001601PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1603 "NoneType",
1604 0,
1605 0,
1606 none_dealloc, /*tp_dealloc*/ /*never called*/
1607 0, /*tp_print*/
1608 0, /*tp_getattr*/
1609 0, /*tp_setattr*/
1610 0, /*tp_reserved*/
1611 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001612 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 0, /*tp_as_sequence*/
1614 0, /*tp_as_mapping*/
1615 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001616 0, /*tp_call */
1617 0, /*tp_str */
1618 0, /*tp_getattro */
1619 0, /*tp_setattro */
1620 0, /*tp_as_buffer */
1621 Py_TPFLAGS_DEFAULT, /*tp_flags */
1622 0, /*tp_doc */
1623 0, /*tp_traverse */
1624 0, /*tp_clear */
1625 0, /*tp_richcompare */
1626 0, /*tp_weaklistoffset */
1627 0, /*tp_iter */
1628 0, /*tp_iternext */
1629 0, /*tp_methods */
1630 0, /*tp_members */
1631 0, /*tp_getset */
1632 0, /*tp_base */
1633 0, /*tp_dict */
1634 0, /*tp_descr_get */
1635 0, /*tp_descr_set */
1636 0, /*tp_dictoffset */
1637 0, /*tp_init */
1638 0, /*tp_alloc */
1639 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001640};
1641
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001642PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001643 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001644 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001645};
1646
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001647/* NotImplemented is an object that can be used to signal that an
1648 operation is not implemented for the given type combination. */
1649
1650static PyObject *
1651NotImplemented_repr(PyObject *op)
1652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001654}
1655
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001656static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301657NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001658{
1659 return PyUnicode_FromString("NotImplemented");
1660}
1661
1662static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301663 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001664 {NULL, NULL}
1665};
1666
1667static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001668notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1669{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001670 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001671 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1672 return NULL;
1673 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001674 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001675}
1676
Armin Ronacher226b1db2012-10-06 14:28:58 +02001677static void
1678notimplemented_dealloc(PyObject* ignore)
1679{
1680 /* This should never get called, but we also don't want to SEGV if
1681 * we accidentally decref NotImplemented out of existence.
1682 */
1683 Py_FatalError("deallocating NotImplemented");
1684}
1685
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001686PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1688 "NotImplementedType",
1689 0,
1690 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001691 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 0, /*tp_print*/
1693 0, /*tp_getattr*/
1694 0, /*tp_setattr*/
1695 0, /*tp_reserved*/
1696 NotImplemented_repr, /*tp_repr*/
1697 0, /*tp_as_number*/
1698 0, /*tp_as_sequence*/
1699 0, /*tp_as_mapping*/
1700 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001701 0, /*tp_call */
1702 0, /*tp_str */
1703 0, /*tp_getattro */
1704 0, /*tp_setattro */
1705 0, /*tp_as_buffer */
1706 Py_TPFLAGS_DEFAULT, /*tp_flags */
1707 0, /*tp_doc */
1708 0, /*tp_traverse */
1709 0, /*tp_clear */
1710 0, /*tp_richcompare */
1711 0, /*tp_weaklistoffset */
1712 0, /*tp_iter */
1713 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001714 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001715 0, /*tp_members */
1716 0, /*tp_getset */
1717 0, /*tp_base */
1718 0, /*tp_dict */
1719 0, /*tp_descr_get */
1720 0, /*tp_descr_set */
1721 0, /*tp_dictoffset */
1722 0, /*tp_init */
1723 0, /*tp_alloc */
1724 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001725};
1726
1727PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001729 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001730};
1731
Guido van Rossumba21a492001-08-16 08:17:26 +00001732void
1733_Py_ReadyTypes(void)
1734{
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001735 if (PyType_Ready(&PyBaseObject_Type) < 0)
1736 Py_FatalError("Can't initialize object type");
1737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 if (PyType_Ready(&PyType_Type) < 0)
1739 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1742 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1745 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1748 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001749
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001750 if (PyType_Ready(&PyLong_Type) < 0)
1751 Py_FatalError("Can't initialize int type");
1752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 if (PyType_Ready(&PyBool_Type) < 0)
1754 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (PyType_Ready(&PyByteArray_Type) < 0)
1757 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (PyType_Ready(&PyBytes_Type) < 0)
1760 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (PyType_Ready(&PyList_Type) < 0)
1763 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001764
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001765 if (PyType_Ready(&_PyNone_Type) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001767
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001768 if (PyType_Ready(&_PyNotImplemented_Type) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (PyType_Ready(&PyTraceBack_Type) < 0)
1772 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (PyType_Ready(&PySuper_Type) < 0)
1775 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (PyType_Ready(&PyRange_Type) < 0)
1778 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (PyType_Ready(&PyDict_Type) < 0)
1781 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001782
Benjamin Petersondb87c992016-11-06 13:01:07 -08001783 if (PyType_Ready(&PyDictKeys_Type) < 0)
1784 Py_FatalError("Can't initialize dict keys type");
1785
1786 if (PyType_Ready(&PyDictValues_Type) < 0)
1787 Py_FatalError("Can't initialize dict values type");
1788
1789 if (PyType_Ready(&PyDictItems_Type) < 0)
1790 Py_FatalError("Can't initialize dict items type");
1791
Eric Snow96c6af92015-05-29 22:21:39 -06001792 if (PyType_Ready(&PyODict_Type) < 0)
1793 Py_FatalError("Can't initialize OrderedDict type");
1794
1795 if (PyType_Ready(&PyODictKeys_Type) < 0)
1796 Py_FatalError("Can't initialize odict_keys type");
1797
1798 if (PyType_Ready(&PyODictItems_Type) < 0)
1799 Py_FatalError("Can't initialize odict_items type");
1800
1801 if (PyType_Ready(&PyODictValues_Type) < 0)
1802 Py_FatalError("Can't initialize odict_values type");
1803
1804 if (PyType_Ready(&PyODictIter_Type) < 0)
1805 Py_FatalError("Can't initialize odict_keyiterator type");
1806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (PyType_Ready(&PySet_Type) < 0)
1808 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 if (PyType_Ready(&PyUnicode_Type) < 0)
1811 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 if (PyType_Ready(&PySlice_Type) < 0)
1814 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1817 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (PyType_Ready(&PyComplex_Type) < 0)
1820 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (PyType_Ready(&PyFloat_Type) < 0)
1823 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1826 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (PyType_Ready(&PyProperty_Type) < 0)
1829 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001830
Stefan Krah9a2d99e2012-02-25 12:24:21 +01001831 if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
1832 Py_FatalError("Can't initialize managed buffer type");
1833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (PyType_Ready(&PyMemoryView_Type) < 0)
1835 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 if (PyType_Ready(&PyTuple_Type) < 0)
1838 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 if (PyType_Ready(&PyEnum_Type) < 0)
1841 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (PyType_Ready(&PyReversed_Type) < 0)
1844 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1847 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (PyType_Ready(&PyCode_Type) < 0)
1850 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (PyType_Ready(&PyFrame_Type) < 0)
1853 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (PyType_Ready(&PyCFunction_Type) < 0)
1856 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (PyType_Ready(&PyMethod_Type) < 0)
1859 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (PyType_Ready(&PyFunction_Type) < 0)
1862 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 if (PyType_Ready(&PyDictProxy_Type) < 0)
1865 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (PyType_Ready(&PyGen_Type) < 0)
1868 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1871 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1874 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001875
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001876 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1877 Py_FatalError("Can't initialize method wrapper type");
1878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 if (PyType_Ready(&PyEllipsis_Type) < 0)
1880 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1883 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001884
Barry Warsaw409da152012-06-03 16:18:47 -04001885 if (PyType_Ready(&_PyNamespace_Type) < 0)
1886 Py_FatalError("Can't initialize namespace type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -04001887
Benjamin Petersonc4311282012-10-30 23:21:10 -04001888 if (PyType_Ready(&PyCapsule_Type) < 0)
1889 Py_FatalError("Can't initialize capsule type");
1890
1891 if (PyType_Ready(&PyLongRangeIter_Type) < 0)
1892 Py_FatalError("Can't initialize long range iterator type");
1893
1894 if (PyType_Ready(&PyCell_Type) < 0)
1895 Py_FatalError("Can't initialize cell type");
1896
1897 if (PyType_Ready(&PyInstanceMethod_Type) < 0)
1898 Py_FatalError("Can't initialize instance method type");
1899
1900 if (PyType_Ready(&PyClassMethodDescr_Type) < 0)
1901 Py_FatalError("Can't initialize class method descr type");
1902
1903 if (PyType_Ready(&PyMethodDescr_Type) < 0)
1904 Py_FatalError("Can't initialize method descr type");
1905
1906 if (PyType_Ready(&PyCallIter_Type) < 0)
1907 Py_FatalError("Can't initialize call iter type");
1908
1909 if (PyType_Ready(&PySeqIter_Type) < 0)
1910 Py_FatalError("Can't initialize sequence iterator type");
Yury Selivanov5376ba92015-06-22 12:19:30 -04001911
1912 if (PyType_Ready(&PyCoro_Type) < 0)
1913 Py_FatalError("Can't initialize coroutine type");
1914
1915 if (PyType_Ready(&_PyCoroWrapper_Type) < 0)
1916 Py_FatalError("Can't initialize coroutine wrapper type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001917}
1918
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001919
Guido van Rossum84a90321996-05-22 16:34:47 +00001920#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001921
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001922void
Fred Drake100814d2000-07-09 15:48:49 +00001923_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001924{
Victor Stinner9e00e802018-10-25 13:31:16 +02001925 if (_Py_tracemalloc_config.tracing) {
1926 _PyTraceMalloc_NewReference(op);
1927 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 _Py_INC_REFTOTAL;
1929 op->ob_refcnt = 1;
1930 _Py_AddToAllObjects(op, 1);
1931 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001932}
1933
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001934void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001935_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001936{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001937#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001938 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001939#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 if (op->ob_refcnt < 0)
1941 Py_FatalError("UNREF negative refcnt");
1942 if (op == &refchain ||
1943 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1944 fprintf(stderr, "* ob\n");
1945 _PyObject_Dump(op);
1946 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1947 _PyObject_Dump(op->_ob_prev->_ob_next);
1948 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1949 _PyObject_Dump(op->_ob_next->_ob_prev);
1950 Py_FatalError("UNREF invalid object");
1951 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001952#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1954 if (p == op)
1955 break;
1956 }
1957 if (p == &refchain) /* Not found */
1958 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001959#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 op->_ob_next->_ob_prev = op->_ob_prev;
1961 op->_ob_prev->_ob_next = op->_ob_next;
1962 op->_ob_next = op->_ob_prev = NULL;
1963 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001964}
1965
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001966void
Fred Drake100814d2000-07-09 15:48:49 +00001967_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1970 _Py_ForgetReference(op);
1971 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001972}
1973
Tim Peters269b2a62003-04-17 19:52:29 +00001974/* Print all live objects. Because PyObject_Print is called, the
1975 * interpreter must be in a healthy state.
1976 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001977void
Fred Drake100814d2000-07-09 15:48:49 +00001978_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PyObject *op;
1981 fprintf(fp, "Remaining objects:\n");
1982 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1983 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1984 if (PyObject_Print(op, fp, 0) != 0)
1985 PyErr_Clear();
1986 putc('\n', fp);
1987 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001988}
1989
Tim Peters269b2a62003-04-17 19:52:29 +00001990/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1991 * doesn't make any calls to the Python C API, so is always safe to call.
1992 */
1993void
1994_Py_PrintReferenceAddresses(FILE *fp)
1995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 PyObject *op;
1997 fprintf(fp, "Remaining object addresses:\n");
1998 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1999 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
2000 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00002001}
2002
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002003PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00002004_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 int i, n;
2007 PyObject *t = NULL;
2008 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2011 return NULL;
2012 op = refchain._ob_next;
2013 res = PyList_New(0);
2014 if (res == NULL)
2015 return NULL;
2016 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2017 while (op == self || op == args || op == res || op == t ||
2018 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2019 op = op->_ob_next;
2020 if (op == &refchain)
2021 return res;
2022 }
2023 if (PyList_Append(res, op) < 0) {
2024 Py_DECREF(res);
2025 return NULL;
2026 }
2027 op = op->_ob_next;
2028 }
2029 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00002030}
2031
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002032#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00002033
Benjamin Petersonb173f782009-05-05 22:31:58 +00002034
Guido van Rossum84a90321996-05-22 16:34:47 +00002035/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002036Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00002037
2038
David Malcolm49526f42012-06-22 14:55:41 -04002039void
2040_PyObject_DebugTypeStats(FILE *out)
2041{
2042 _PyCFunction_DebugMallocStats(out);
2043 _PyDict_DebugMallocStats(out);
2044 _PyFloat_DebugMallocStats(out);
2045 _PyFrame_DebugMallocStats(out);
2046 _PyList_DebugMallocStats(out);
2047 _PyMethod_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04002048 _PyTuple_DebugMallocStats(out);
2049}
Guido van Rossumb18618d2000-05-03 23:44:39 +00002050
Guido van Rossum86610361998-04-10 22:32:46 +00002051/* These methods are used to control infinite recursion in repr, str, print,
2052 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00002053 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00002054 Py_ReprLeave() to avoid infinite recursion.
2055
2056 Py_ReprEnter() returns 0 the first time it is called for a particular
2057 object and 1 every time thereafter. It returns -1 if an exception
2058 occurred. Py_ReprLeave() has no return value.
2059
2060 See dictobject.c and listobject.c for examples of use.
2061*/
2062
Guido van Rossum86610361998-04-10 22:32:46 +00002063int
Fred Drake100814d2000-07-09 15:48:49 +00002064Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 PyObject *dict;
2067 PyObject *list;
2068 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02002071 /* Ignore a missing thread-state, so that this function can be called
2072 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (dict == NULL)
2074 return 0;
Victor Stinner7a07e452013-11-06 18:57:29 +01002075 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 if (list == NULL) {
2077 list = PyList_New(0);
2078 if (list == NULL)
2079 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01002080 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 return -1;
2082 Py_DECREF(list);
2083 }
2084 i = PyList_GET_SIZE(list);
2085 while (--i >= 0) {
2086 if (PyList_GET_ITEM(list, i) == obj)
2087 return 1;
2088 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002089 if (PyList_Append(list, obj) < 0)
2090 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002092}
2093
2094void
Fred Drake100814d2000-07-09 15:48:49 +00002095Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 PyObject *dict;
2098 PyObject *list;
2099 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002100 PyObject *error_type, *error_value, *error_traceback;
2101
2102 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 dict = PyThreadState_GetDict();
2105 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002106 goto finally;
2107
Victor Stinner7a07e452013-11-06 18:57:29 +01002108 list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002110 goto finally;
2111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 i = PyList_GET_SIZE(list);
2113 /* Count backwards because we always expect obj to be list[-1] */
2114 while (--i >= 0) {
2115 if (PyList_GET_ITEM(list, i) == obj) {
2116 PyList_SetSlice(list, i, i + 1, NULL);
2117 break;
2118 }
2119 }
Victor Stinner1b634932013-07-16 22:24:44 +02002120
2121finally:
2122 /* ignore exceptions because there is no way to report them. */
2123 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002124}
Guido van Rossumd724b232000-03-13 16:01:29 +00002125
Tim Peters803526b2002-07-07 05:13:56 +00002126/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002127
Tim Peters803526b2002-07-07 05:13:56 +00002128/* Add op to the _PyTrash_delete_later list. Called when the current
2129 * call-stack depth gets large. op must be a currently untracked gc'ed
2130 * object, with refcount 0. Py_DECREF must already have been called on it.
2131 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002132void
Fred Drake100814d2000-07-09 15:48:49 +00002133_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 assert(PyObject_IS_GC(op));
INADA Naokid8521422018-05-17 11:07:21 +09002136 assert(!_PyObject_GC_IS_TRACKED(op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 assert(op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002138 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002139 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002140}
2141
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002142/* The equivalent API, using per-thread state recursion info */
2143void
2144_PyTrash_thread_deposit_object(PyObject *op)
2145{
2146 PyThreadState *tstate = PyThreadState_GET();
2147 assert(PyObject_IS_GC(op));
INADA Naokid8521422018-05-17 11:07:21 +09002148 assert(!_PyObject_GC_IS_TRACKED(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002149 assert(op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002150 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002151 tstate->trash_delete_later = op;
2152}
2153
Tim Peters803526b2002-07-07 05:13:56 +00002154/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2155 * the call-stack unwinds again.
2156 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002157void
Fred Drake100814d2000-07-09 15:48:49 +00002158_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002159{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002160 while (_PyRuntime.gc.trash_delete_later) {
2161 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002163
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002164 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002165 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* Call the deallocator directly. This used to try to
2168 * fool Py_DECREF into calling it indirectly, but
2169 * Py_DECREF was already called on this object, and in
2170 * assorted non-release builds calling Py_DECREF again ends
2171 * up distorting allocation statistics.
2172 */
2173 assert(op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002174 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002176 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002178}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002179
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002180/* The equivalent API, using per-thread state recursion info */
2181void
2182_PyTrash_thread_destroy_chain(void)
2183{
2184 PyThreadState *tstate = PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002185 /* We need to increase trash_delete_nesting here, otherwise,
2186 _PyTrash_thread_destroy_chain will be called recursively
2187 and then possibly crash. An example that may crash without
2188 increase:
2189 N = 500000 # need to be large enough
2190 ob = object()
2191 tups = [(ob,) for i in range(N)]
2192 for i in range(49):
2193 tups = [(tup,) for tup in tups]
2194 del tups
2195 */
2196 assert(tstate->trash_delete_nesting == 0);
2197 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002198 while (tstate->trash_delete_later) {
2199 PyObject *op = tstate->trash_delete_later;
2200 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2201
2202 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002203 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002204
2205 /* Call the deallocator directly. This used to try to
2206 * fool Py_DECREF into calling it indirectly, but
2207 * Py_DECREF was already called on this object, and in
2208 * assorted non-release builds calling Py_DECREF again ends
2209 * up distorting allocation statistics.
2210 */
2211 assert(op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002212 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002213 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002214 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002215 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002216}
2217
Victor Stinner626bff82018-10-25 17:31:10 +02002218
2219void
2220_PyObject_AssertFailed(PyObject *obj, const char *msg, const char *expr,
2221 const char *file, int line, const char *function)
2222{
2223 fprintf(stderr,
2224 "%s:%d: %s: Assertion \"%s\" failed",
2225 file, line, function, expr);
2226 fflush(stderr);
2227
2228 if (msg) {
2229 fprintf(stderr, "; %s.\n", msg);
2230 }
2231 else {
2232 fprintf(stderr, ".\n");
2233 }
2234 fflush(stderr);
2235
2236 if (obj == NULL) {
2237 fprintf(stderr, "<NULL object>\n");
2238 }
2239 else if (_PyObject_IsFreed(obj)) {
2240 /* It seems like the object memory has been freed:
2241 don't access it to prevent a segmentation fault. */
2242 fprintf(stderr, "<Freed object>\n");
2243 }
2244 else {
2245 /* Diplay the traceback where the object has been allocated.
2246 Do it before dumping repr(obj), since repr() is more likely
2247 to crash than dumping the traceback. */
2248 void *ptr;
2249 PyTypeObject *type = Py_TYPE(obj);
2250 if (PyType_IS_GC(type)) {
2251 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2252 }
2253 else {
2254 ptr = (void *)obj;
2255 }
2256 _PyMem_DumpTraceback(fileno(stderr), ptr);
2257
2258 /* This might succeed or fail, but we're about to abort, so at least
2259 try to provide any extra info we can: */
2260 _PyObject_Dump(obj);
2261 }
2262 fflush(stderr);
2263
2264 Py_FatalError("_PyObject_AssertFailed");
2265}
2266
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002267#ifndef Py_TRACE_REFS
2268/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
2269 Define this here, so we can undefine the macro. */
2270#undef _Py_Dealloc
Benjamin Petersone5024512018-09-12 12:06:42 -07002271void _Py_Dealloc(PyObject *);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002272void
2273_Py_Dealloc(PyObject *op)
2274{
2275 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
2276 (*Py_TYPE(op)->tp_dealloc)(op);
2277}
2278#endif
2279
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002280#ifdef __cplusplus
2281}
2282#endif