blob: 2c8e823f05ee9414284cf5d7a2cc08ab958bd90c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Benjamin Peterson722954a2011-06-11 16:33:35 -05002/* Generic object operations; and implementation of None */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02005#include "pycore_initconfig.h"
Victor Stinner0fc91ee2019-04-12 21:51:34 +02006#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pystate.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01008#include "pycore_context.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00009#include "frameobject.h"
Eric Snowc11183c2019-03-15 16:35:46 -060010#include "interpreteridobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012#ifdef __cplusplus
13extern "C" {
14#endif
15
Victor Stinner626bff82018-10-25 17:31:10 +020016/* Defined in tracemalloc.c */
17extern void _PyMem_DumpTraceback(int fd, const void *ptr);
18
Victor Stinnerbd303c12013-11-07 23:07:29 +010019_Py_IDENTIFIER(Py_Repr);
20_Py_IDENTIFIER(__bytes__);
21_Py_IDENTIFIER(__dir__);
22_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010023
Victor Stinner0fc91ee2019-04-12 21:51:34 +020024
25int
26_PyObject_CheckConsistency(PyObject *op, int check_content)
27{
Victor Stinner68762572019-10-07 18:42:01 +020028#define CHECK(expr) \
29 do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
Victor Stinner0fc91ee2019-04-12 21:51:34 +020030
Victor Stinner68762572019-10-07 18:42:01 +020031 CHECK(!_PyObject_IsFreed(op));
32 CHECK(Py_REFCNT(op) >= 1);
33
34 CHECK(op->ob_type != NULL);
35 _PyType_CheckConsistency(op->ob_type);
Victor Stinner0fc91ee2019-04-12 21:51:34 +020036
37 if (PyUnicode_Check(op)) {
38 _PyUnicode_CheckConsistency(op, check_content);
39 }
40 else if (PyDict_Check(op)) {
41 _PyDict_CheckConsistency(op, check_content);
42 }
43 return 1;
Victor Stinner68762572019-10-07 18:42:01 +020044
45#undef CHECK
Victor Stinner0fc91ee2019-04-12 21:51:34 +020046}
47
48
Tim Peters34592512002-07-11 06:23:50 +000049#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000050Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051
52Py_ssize_t
53_Py_GetRefTotal(void)
54{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 PyObject *o;
56 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020057 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (o != NULL)
59 total -= o->ob_refcnt;
60 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000061}
Nick Coghland6009512014-11-20 21:39:37 +100062
63void
64_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070065 fprintf(stderr,
66 "[%" PY_FORMAT_SIZE_T "d refs, "
67 "%" PY_FORMAT_SIZE_T "d blocks]\n",
68 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100069}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000070#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071
Guido van Rossum3f5da241990-12-20 15:06:42 +000072/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
73 These are used by the individual routines for object creation.
74 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075
Tim Peters78be7992003-03-23 02:51:01 +000076#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000077/* Head of circular doubly-linked list of all objects. These are linked
78 * together via the _ob_prev and _ob_next members of a PyObject, which
79 * exist only in a Py_TRACE_REFS build.
80 */
Tim Peters78be7992003-03-23 02:51:01 +000081static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000082
Tim Peters7571a0f2003-03-23 17:52:28 +000083/* Insert op at the front of the list of all objects. If force is true,
84 * op is added even if _ob_prev and _ob_next are non-NULL already. If
85 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
86 * force should be true if and only if op points to freshly allocated,
87 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000088 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000089 * Note that objects are normally added to the list via _Py_NewReference,
90 * which is called by PyObject_Init. Not all objects are initialized that
91 * way, though; exceptions include statically allocated type objects, and
92 * statically allocated singletons (like Py_True and Py_None).
93 */
Tim Peters36eb4df2003-03-23 03:33:13 +000094void
Tim Peters7571a0f2003-03-23 17:52:28 +000095_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000096{
Tim Peters7571a0f2003-03-23 17:52:28 +000097#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 if (!force) {
99 /* If it's initialized memory, op must be in or out of
100 * the list unambiguously.
101 */
Victor Stinner24702042018-10-26 17:16:37 +0200102 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 }
Tim Peters78be7992003-03-23 02:51:01 +0000104#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 if (force || op->_ob_prev == NULL) {
106 op->_ob_next = refchain._ob_next;
107 op->_ob_prev = &refchain;
108 refchain._ob_next->_ob_prev = op;
109 refchain._ob_next = op;
110 }
Tim Peters7571a0f2003-03-23 17:52:28 +0000111}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +0000113
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000114#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000116/* All types are added to type_list, at least when
117 they get one object created. That makes them
118 immortal, which unfortunately contributes to
119 garbage itself. If unlist_types_without_objects
120 is set, they will be removed from the type_list
121 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +0000122static int unlist_types_without_objects;
Pablo Galindo49c75a82018-10-28 15:02:17 +0000123extern Py_ssize_t _Py_tuple_zero_allocs, _Py_fast_tuple_allocs;
124extern Py_ssize_t _Py_quick_int_allocs, _Py_quick_neg_int_allocs;
125extern Py_ssize_t _Py_null_strings, _Py_one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000126void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000127_Py_dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000128{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200129 PyInterpreterState *interp = _PyInterpreterState_Get();
Victor Stinner331a6a52019-05-27 16:39:22 +0200130 if (!interp->config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300131 return;
Victor Stinner25420fe2017-11-20 18:12:22 -0800132 }
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000133
Eddie Elizondo745dc652018-02-21 20:55:18 -0800134 PyTypeObject *tp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 for (tp = type_list; tp; tp = tp->tp_next)
136 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
137 "freed: %" PY_FORMAT_SIZE_T "d, "
138 "max in use: %" PY_FORMAT_SIZE_T "d\n",
139 tp->tp_name, tp->tp_allocs, tp->tp_frees,
140 tp->tp_maxalloc);
141 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
142 "empty: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000143 _Py_fast_tuple_allocs, _Py_tuple_zero_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
145 "neg: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000146 _Py_quick_int_allocs, _Py_quick_neg_int_allocs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
148 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
Pablo Galindo49c75a82018-10-28 15:02:17 +0000149 _Py_null_strings, _Py_one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000150}
151
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000152PyObject *
Pablo Galindo49c75a82018-10-28 15:02:17 +0000153_Py_get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 PyTypeObject *tp;
156 PyObject *result;
157 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 result = PyList_New(0);
160 if (result == NULL)
161 return NULL;
162 for (tp = type_list; tp; tp = tp->tp_next) {
163 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
164 tp->tp_frees, tp->tp_maxalloc);
165 if (v == NULL) {
166 Py_DECREF(result);
167 return NULL;
168 }
169 if (PyList_Append(result, v) < 0) {
170 Py_DECREF(v);
171 Py_DECREF(result);
172 return NULL;
173 }
174 Py_DECREF(v);
175 }
176 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000177}
178
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000179void
Pablo Galindo49c75a82018-10-28 15:02:17 +0000180_Py_inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
183 /* first time; insert in linked list */
184 if (tp->tp_next != NULL) /* sanity check */
Pablo Galindo49c75a82018-10-28 15:02:17 +0000185 Py_FatalError("XXX _Py_inc_count sanity check");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (type_list)
187 type_list->tp_prev = tp;
188 tp->tp_next = type_list;
189 /* Note that as of Python 2.2, heap-allocated type objects
190 * can go away, but this code requires that they stay alive
191 * until program exit. That's why we're careful with
192 * refcounts here. type_list gets a new reference to tp,
193 * while ownership of the reference type_list used to hold
194 * (if any) was transferred to tp->tp_next in the line above.
195 * tp is thus effectively immortal after this.
196 */
197 Py_INCREF(tp);
198 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000199#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 /* Also insert in the doubly-linked list of all objects,
201 * if not already there.
202 */
203 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000204#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 }
206 tp->tp_allocs++;
207 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
208 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000209}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000210
Pablo Galindo49c75a82018-10-28 15:02:17 +0000211void _Py_dec_count(PyTypeObject *tp)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 tp->tp_frees++;
214 if (unlist_types_without_objects &&
215 tp->tp_allocs == tp->tp_frees) {
216 /* unlink the type from type_list */
217 if (tp->tp_prev)
218 tp->tp_prev->tp_next = tp->tp_next;
219 else
220 type_list = tp->tp_next;
221 if (tp->tp_next)
222 tp->tp_next->tp_prev = tp->tp_prev;
223 tp->tp_next = tp->tp_prev = NULL;
224 Py_DECREF(tp);
225 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000226}
227
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000228#endif
229
Tim Peters7c321a82002-07-09 02:57:01 +0000230#ifdef Py_REF_DEBUG
231/* Log a fatal error; doesn't return. */
232void
Victor Stinner18618e652018-10-25 17:28:11 +0200233_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000234{
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100235 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200236 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000237}
238
239#endif /* Py_REF_DEBUG */
240
Thomas Heller1328b522004-04-22 17:23:49 +0000241void
242Py_IncRef(PyObject *o)
243{
244 Py_XINCREF(o);
245}
246
247void
248Py_DecRef(PyObject *o)
249{
250 Py_XDECREF(o);
251}
252
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000253PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000254PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 if (op == NULL)
257 return PyErr_NoMemory();
258 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
259 Py_TYPE(op) = tp;
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400260 if (PyType_GetFlags(tp) & Py_TPFLAGS_HEAPTYPE) {
261 Py_INCREF(tp);
262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 _Py_NewReference(op);
264 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000265}
266
Guido van Rossumb18618d2000-05-03 23:44:39 +0000267PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000268PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 if (op == NULL)
271 return (PyVarObject *) PyErr_NoMemory();
272 /* Any changes should be reflected in PyObject_INIT_VAR */
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400273 Py_SIZE(op) = size;
274 PyObject_Init((PyObject *)op, tp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000276}
277
278PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000279_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *op;
282 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
283 if (op == NULL)
284 return PyErr_NoMemory();
285 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000286}
287
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000288PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000289_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 PyVarObject *op;
292 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
293 op = (PyVarObject *) PyObject_MALLOC(size);
294 if (op == NULL)
295 return (PyVarObject *)PyErr_NoMemory();
296 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000297}
298
Antoine Pitrou796564c2013-07-30 19:59:21 +0200299void
300PyObject_CallFinalizer(PyObject *self)
301{
302 PyTypeObject *tp = Py_TYPE(self);
303
Antoine Pitrouada319b2019-05-29 22:12:38 +0200304 if (tp->tp_finalize == NULL)
Antoine Pitrou796564c2013-07-30 19:59:21 +0200305 return;
306 /* tp_finalize should only be called once. */
307 if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
308 return;
309
310 tp->tp_finalize(self);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900311 if (PyType_IS_GC(tp)) {
312 _PyGC_SET_FINALIZED(self);
313 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200314}
315
316int
317PyObject_CallFinalizerFromDealloc(PyObject *self)
318{
319 Py_ssize_t refcnt;
320
321 /* Temporarily resurrect the object. */
322 if (self->ob_refcnt != 0) {
323 Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
324 "object with a non-zero refcount");
325 }
326 self->ob_refcnt = 1;
327
328 PyObject_CallFinalizer(self);
329
330 /* Undo the temporary resurrection; can't use DECREF here, it would
331 * cause a recursive call.
332 */
Victor Stinner24702042018-10-26 17:16:37 +0200333 _PyObject_ASSERT_WITH_MSG(self,
334 self->ob_refcnt > 0,
335 "refcount is too small");
Antoine Pitrou796564c2013-07-30 19:59:21 +0200336 if (--self->ob_refcnt == 0)
337 return 0; /* this is the normal path out */
338
339 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
340 * never happened.
341 */
342 refcnt = self->ob_refcnt;
343 _Py_NewReference(self);
344 self->ob_refcnt = refcnt;
345
Victor Stinner24702042018-10-26 17:16:37 +0200346 _PyObject_ASSERT(self,
347 (!PyType_IS_GC(Py_TYPE(self))
348 || _PyObject_GC_IS_TRACKED(self)));
Antoine Pitrou796564c2013-07-30 19:59:21 +0200349 /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
350 * we need to undo that. */
351 _Py_DEC_REFTOTAL;
352 /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
353 * chain, so no more to do there.
354 * If COUNT_ALLOCS, the original decref bumped tp_frees, and
355 * _Py_NewReference bumped tp_allocs: both of those need to be
356 * undone.
357 */
358#ifdef COUNT_ALLOCS
359 --Py_TYPE(self)->tp_frees;
360 --Py_TYPE(self)->tp_allocs;
361#endif
362 return -1;
363}
364
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000365int
366PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (PyErr_CheckSignals())
370 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000371#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (PyOS_CheckStack()) {
373 PyErr_SetString(PyExc_MemoryError, "stack overflow");
374 return -1;
375 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000376#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 clearerr(fp); /* Clear any previous error condition */
378 if (op == NULL) {
379 Py_BEGIN_ALLOW_THREADS
380 fprintf(fp, "<nil>");
381 Py_END_ALLOW_THREADS
382 }
383 else {
Victor Stinner3ec9af72018-10-26 02:12:34 +0200384 if (op->ob_refcnt <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* XXX(twouters) cast refcount to long until %zd is
386 universally available */
387 Py_BEGIN_ALLOW_THREADS
388 fprintf(fp, "<refcnt %ld at %p>",
Zackery Spytz1a2252e2019-05-06 10:56:51 -0600389 (long)op->ob_refcnt, (void *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200391 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 else {
393 PyObject *s;
394 if (flags & Py_PRINT_RAW)
395 s = PyObject_Str(op);
396 else
397 s = PyObject_Repr(op);
398 if (s == NULL)
399 ret = -1;
400 else if (PyBytes_Check(s)) {
401 fwrite(PyBytes_AS_STRING(s), 1,
402 PyBytes_GET_SIZE(s), fp);
403 }
404 else if (PyUnicode_Check(s)) {
405 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200406 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600407 if (t == NULL) {
408 ret = -1;
409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 else {
411 fwrite(PyBytes_AS_STRING(t), 1,
412 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000413 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 }
415 }
416 else {
417 PyErr_Format(PyExc_TypeError,
418 "str() or repr() returned '%.100s'",
419 s->ob_type->tp_name);
420 ret = -1;
421 }
422 Py_XDECREF(s);
423 }
424 }
425 if (ret == 0) {
426 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300427 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 clearerr(fp);
429 ret = -1;
430 }
431 }
432 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433}
434
Guido van Rossum38938152006-08-21 23:36:26 +0000435/* For debugging convenience. Set a breakpoint here and call it from your DLL */
436void
Thomas Woutersb2137042007-02-01 18:02:27 +0000437_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000438{
439}
440
Neal Norwitz1a997502003-01-13 20:13:12 +0000441
Victor Stinner4c409be2019-04-11 13:01:15 +0200442/* Heuristic checking if the object memory is uninitialized or deallocated.
443 Rely on the debug hooks on Python memory allocators:
444 see _PyMem_IsPtrFreed().
Victor Stinner82af0b62018-10-23 17:39:40 +0200445
446 The function can be used to prevent segmentation fault on dereferencing
Victor Stinner4c409be2019-04-11 13:01:15 +0200447 pointers like 0xDDDDDDDDDDDDDDDD. */
Victor Stinner82af0b62018-10-23 17:39:40 +0200448int
449_PyObject_IsFreed(PyObject *op)
450{
Victor Stinner2b00db62019-04-11 11:33:27 +0200451 if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(op->ob_type)) {
Victor Stinner2cf5d322018-11-22 16:32:57 +0100452 return 1;
453 }
Victor Stinner2b00db62019-04-11 11:33:27 +0200454 /* ignore op->ob_ref: its value can have be modified
Victor Stinner82af0b62018-10-23 17:39:40 +0200455 by Py_INCREF() and Py_DECREF(). */
456#ifdef Py_TRACE_REFS
Pablo Galindo36e33c32019-10-08 00:43:14 +0100457 if (op->_ob_next != NULL && _PyMem_IsPtrFreed(op->_ob_next)) {
Victor Stinner2b00db62019-04-11 11:33:27 +0200458 return 1;
459 }
Pablo Galindo36e33c32019-10-08 00:43:14 +0100460 if (op->_ob_prev != NULL && _PyMem_IsPtrFreed(op->_ob_prev)) {
461 return 1;
462 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200463#endif
Victor Stinner2b00db62019-04-11 11:33:27 +0200464 return 0;
Victor Stinner82af0b62018-10-23 17:39:40 +0200465}
466
467
Barry Warsaw9bf16442001-01-23 16:24:35 +0000468/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000469void
470_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000471{
Victor Stinner82af0b62018-10-23 17:39:40 +0200472 if (_PyObject_IsFreed(op)) {
473 /* It seems like the object memory has been freed:
474 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +0200475 fprintf(stderr, "<object at %p is freed>\n", op);
Victor Stinner68762572019-10-07 18:42:01 +0200476 fflush(stderr);
Victor Stinner2cf5d322018-11-22 16:32:57 +0100477 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200478 }
479
Victor Stinner68762572019-10-07 18:42:01 +0200480 /* first, write fields which are the least likely to crash */
481 fprintf(stderr, "object address : %p\n", (void *)op);
Victor Stinner82af0b62018-10-23 17:39:40 +0200482 /* XXX(twouters) cast refcount to long until %zd is
483 universally available */
Victor Stinner68762572019-10-07 18:42:01 +0200484 fprintf(stderr, "object refcount : %ld\n", (long)op->ob_refcnt);
485 fflush(stderr);
486
487 PyTypeObject *type = Py_TYPE(op);
488 fprintf(stderr, "object type : %p\n", type);
489 fprintf(stderr, "object type name: %s\n",
490 type==NULL ? "NULL" : type->tp_name);
491
492 /* the most dangerous part */
493 fprintf(stderr, "object repr : ");
494 fflush(stderr);
495
496 PyGILState_STATE gil = PyGILState_Ensure();
497 PyObject *error_type, *error_value, *error_traceback;
498 PyErr_Fetch(&error_type, &error_value, &error_traceback);
499
500 (void)PyObject_Print(op, stderr, 0);
501 fflush(stderr);
502
503 PyErr_Restore(error_type, error_value, error_traceback);
504 PyGILState_Release(gil);
505
506 fprintf(stderr, "\n");
Victor Stinner82af0b62018-10-23 17:39:40 +0200507 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000508}
Barry Warsaw903138f2001-01-23 16:33:18 +0000509
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000511PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PyObject *res;
514 if (PyErr_CheckSignals())
515 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000516#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (PyOS_CheckStack()) {
518 PyErr_SetString(PyExc_MemoryError, "stack overflow");
519 return NULL;
520 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000521#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (v == NULL)
523 return PyUnicode_FromString("<NULL>");
524 if (Py_TYPE(v)->tp_repr == NULL)
525 return PyUnicode_FromFormat("<%s object at %p>",
526 v->ob_type->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200527
528#ifdef Py_DEBUG
529 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100530 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000531 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200532 assert(!PyErr_Occurred());
533#endif
534
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200535 /* It is possible for a type to have a tp_repr representation that loops
536 infinitely. */
537 if (Py_EnterRecursiveCall(" while getting the repr of an object"))
538 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 res = (*v->ob_type->tp_repr)(v);
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200540 Py_LeaveRecursiveCall();
Victor Stinner0a54cf12011-12-01 03:22:44 +0100541 if (res == NULL)
542 return NULL;
543 if (!PyUnicode_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 PyErr_Format(PyExc_TypeError,
545 "__repr__ returned non-string (type %.200s)",
546 res->ob_type->tp_name);
547 Py_DECREF(res);
548 return NULL;
549 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100550#ifndef Py_DEBUG
551 if (PyUnicode_READY(res) < 0)
552 return NULL;
553#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000555}
556
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000557PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000558PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 PyObject *res;
561 if (PyErr_CheckSignals())
562 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000563#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (PyOS_CheckStack()) {
565 PyErr_SetString(PyExc_MemoryError, "stack overflow");
566 return NULL;
567 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000568#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (v == NULL)
570 return PyUnicode_FromString("<NULL>");
571 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100572#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100573 if (PyUnicode_READY(v) < 0)
574 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100575#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 Py_INCREF(v);
577 return v;
578 }
579 if (Py_TYPE(v)->tp_str == NULL)
580 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000581
Victor Stinner33824f62013-08-26 14:05:19 +0200582#ifdef Py_DEBUG
583 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100584 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000585 caller loses its exception */
Victor Stinner33824f62013-08-26 14:05:19 +0200586 assert(!PyErr_Occurred());
587#endif
588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 /* It is possible for a type to have a tp_str representation that loops
590 infinitely. */
591 if (Py_EnterRecursiveCall(" while getting the str of an object"))
592 return NULL;
593 res = (*Py_TYPE(v)->tp_str)(v);
594 Py_LeaveRecursiveCall();
595 if (res == NULL)
596 return NULL;
597 if (!PyUnicode_Check(res)) {
598 PyErr_Format(PyExc_TypeError,
599 "__str__ returned non-string (type %.200s)",
600 Py_TYPE(res)->tp_name);
601 Py_DECREF(res);
602 return NULL;
603 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100604#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100605 if (PyUnicode_READY(res) < 0)
606 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100607#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100608 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000610}
611
Georg Brandl559e5d72008-06-11 18:37:52 +0000612PyObject *
613PyObject_ASCII(PyObject *v)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 repr = PyObject_Repr(v);
618 if (repr == NULL)
619 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000620
Victor Stinneraf037572013-04-14 18:44:10 +0200621 if (PyUnicode_IS_ASCII(repr))
622 return repr;
623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200625 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 Py_DECREF(repr);
627 if (ascii == NULL)
628 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 res = PyUnicode_DecodeASCII(
631 PyBytes_AS_STRING(ascii),
632 PyBytes_GET_SIZE(ascii),
633 NULL);
634
635 Py_DECREF(ascii);
636 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000637}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000638
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000639PyObject *
640PyObject_Bytes(PyObject *v)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (v == NULL)
645 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (PyBytes_CheckExact(v)) {
648 Py_INCREF(v);
649 return v;
650 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000651
Benjamin Petersonce798522012-01-22 11:24:29 -0500652 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100654 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 Py_DECREF(func);
656 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000657 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000659 PyErr_Format(PyExc_TypeError,
660 "__bytes__ returned non-bytes (type %.200s)",
661 Py_TYPE(result)->tp_name);
662 Py_DECREF(result);
663 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 }
665 return result;
666 }
667 else if (PyErr_Occurred())
668 return NULL;
669 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000670}
671
Mark Dickinsonc008a172009-02-01 13:59:22 +0000672/* For Python 3.0.1 and later, the old three-way comparison has been
673 completely removed in favour of rich comparisons. PyObject_Compare() and
674 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200675 The old tp_compare slot has been renamed to tp_as_async, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000676 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000677
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000678 See (*) below for practical amendments.
679
Mark Dickinsonc008a172009-02-01 13:59:22 +0000680 tp_richcompare gets called with a first argument of the appropriate type
681 and a second object of an arbitrary type. We never do any kind of
682 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000683
Mark Dickinsonc008a172009-02-01 13:59:22 +0000684 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000685
686 NULL if an exception occurred
687 NotImplemented if the requested comparison is not implemented
688 any other false value if the requested comparison is false
689 any other true value if the requested comparison is true
690
691 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
692 NotImplemented.
693
694 (*) Practical amendments:
695
696 - If rich comparison returns NotImplemented, == and != are decided by
697 comparing the object pointer (i.e. falling back to the base object
698 implementation).
699
Guido van Rossuma4073002002-05-31 20:03:54 +0000700*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000701
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000702/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000703int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000704
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200705static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000706
707/* Perform a rich comparison, raising TypeError when the requested comparison
708 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000709static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000710do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 richcmpfunc f;
713 PyObject *res;
714 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (v->ob_type != w->ob_type &&
717 PyType_IsSubtype(w->ob_type, v->ob_type) &&
718 (f = w->ob_type->tp_richcompare) != NULL) {
719 checked_reverse_op = 1;
720 res = (*f)(w, v, _Py_SwappedOp[op]);
721 if (res != Py_NotImplemented)
722 return res;
723 Py_DECREF(res);
724 }
725 if ((f = v->ob_type->tp_richcompare) != NULL) {
726 res = (*f)(v, w, op);
727 if (res != Py_NotImplemented)
728 return res;
729 Py_DECREF(res);
730 }
731 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
732 res = (*f)(w, v, _Py_SwappedOp[op]);
733 if (res != Py_NotImplemented)
734 return res;
735 Py_DECREF(res);
736 }
737 /* If neither object implements it, provide a sensible default
738 for == and !=, but raise an exception for ordering. */
739 switch (op) {
740 case Py_EQ:
741 res = (v == w) ? Py_True : Py_False;
742 break;
743 case Py_NE:
744 res = (v != w) ? Py_True : Py_False;
745 break;
746 default:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyErr_Format(PyExc_TypeError,
Victor Stinner91108f02015-10-14 18:25:31 +0200748 "'%s' not supported between instances of '%.100s' and '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 opstrings[op],
Victor Stinner91108f02015-10-14 18:25:31 +0200750 v->ob_type->tp_name,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 w->ob_type->tp_name);
752 return NULL;
753 }
754 Py_INCREF(res);
755 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000756}
757
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000758/* Perform a rich comparison with object result. This wraps do_richcompare()
759 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000760
Guido van Rossume797ec12001-01-17 15:24:28 +0000761PyObject *
762PyObject_RichCompare(PyObject *v, PyObject *w, int op)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 assert(Py_LT <= op && op <= Py_GE);
767 if (v == NULL || w == NULL) {
768 if (!PyErr_Occurred())
769 PyErr_BadInternalCall();
770 return NULL;
771 }
772 if (Py_EnterRecursiveCall(" in comparison"))
773 return NULL;
774 res = do_richcompare(v, w, op);
775 Py_LeaveRecursiveCall();
776 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000777}
778
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000779/* Perform a rich comparison with integer result. This wraps
780 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000781int
782PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyObject *res;
785 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* Quick result when objects are the same.
788 Guarantees that identity implies equality. */
789 if (v == w) {
790 if (op == Py_EQ)
791 return 1;
792 else if (op == Py_NE)
793 return 0;
794 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 res = PyObject_RichCompare(v, w, op);
797 if (res == NULL)
798 return -1;
799 if (PyBool_Check(res))
800 ok = (res == Py_True);
801 else
802 ok = PyObject_IsTrue(res);
803 Py_DECREF(res);
804 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000805}
Fred Drake13634cf2000-06-29 19:17:04 +0000806
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100807Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000808PyObject_HashNotImplemented(PyObject *v)
809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
811 Py_TYPE(v)->tp_name);
812 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000813}
Fred Drake13634cf2000-06-29 19:17:04 +0000814
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000815Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000816PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyTypeObject *tp = Py_TYPE(v);
819 if (tp->tp_hash != NULL)
820 return (*tp->tp_hash)(v);
821 /* To keep to the general practice that inheriting
822 * solely from object in C code should work without
823 * an explicit call to PyType_Ready, we implicitly call
824 * PyType_Ready here and then check the tp_hash slot again
825 */
826 if (tp->tp_dict == NULL) {
827 if (PyType_Ready(tp) < 0)
828 return -1;
829 if (tp->tp_hash != NULL)
830 return (*tp->tp_hash)(v);
831 }
832 /* Otherwise, the object can't be hashed */
833 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000834}
835
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000836PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000837PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (Py_TYPE(v)->tp_getattr != NULL)
842 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900843 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (w == NULL)
845 return NULL;
846 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100847 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000849}
850
851int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000852PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 PyObject *res = PyObject_GetAttrString(v, name);
855 if (res != NULL) {
856 Py_DECREF(res);
857 return 1;
858 }
859 PyErr_Clear();
860 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000861}
862
863int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000864PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 PyObject *s;
867 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (Py_TYPE(v)->tp_setattr != NULL)
870 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
871 s = PyUnicode_InternFromString(name);
872 if (s == NULL)
873 return -1;
874 res = PyObject_SetAttr(v, s, w);
875 Py_XDECREF(s);
876 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000877}
878
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500879int
880_PyObject_IsAbstract(PyObject *obj)
881{
882 int res;
883 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500884
885 if (obj == NULL)
886 return 0;
887
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200888 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
889 if (res > 0) {
890 res = PyObject_IsTrue(isabstract);
891 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500892 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500893 return res;
894}
895
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000896PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200897_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
898{
899 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100900 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200901 if (!oname)
902 return NULL;
903 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200904 return result;
905}
906
907int
908_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
909{
910 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100911 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200912 if (!oname)
913 return -1;
914 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200915 return result;
916}
917
918int
919_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
920{
921 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100922 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200923 if (!oname)
924 return -1;
925 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200926 return result;
927}
928
929PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000930PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (!PyUnicode_Check(name)) {
935 PyErr_Format(PyExc_TypeError,
936 "attribute name must be string, not '%.200s'",
937 name->ob_type->tp_name);
938 return NULL;
939 }
940 if (tp->tp_getattro != NULL)
941 return (*tp->tp_getattro)(v, name);
942 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200943 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (name_str == NULL)
945 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200946 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
948 PyErr_Format(PyExc_AttributeError,
949 "'%.50s' object has no attribute '%U'",
950 tp->tp_name, name);
951 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000952}
953
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200954int
955_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900956{
957 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900958
959 if (!PyUnicode_Check(name)) {
960 PyErr_Format(PyExc_TypeError,
961 "attribute name must be string, not '%.200s'",
962 name->ob_type->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200963 *result = NULL;
964 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900965 }
966
967 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200968 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
969 if (*result != NULL) {
970 return 1;
971 }
972 if (PyErr_Occurred()) {
973 return -1;
974 }
975 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900976 }
977 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200978 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900979 }
980 else if (tp->tp_getattr != NULL) {
981 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200982 if (name_str == NULL) {
983 *result = NULL;
984 return -1;
985 }
986 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900987 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900988 else {
989 *result = NULL;
990 return 0;
991 }
992
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200993 if (*result != NULL) {
994 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900995 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200996 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
997 return -1;
998 }
999 PyErr_Clear();
1000 return 0;
1001}
1002
1003int
1004_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
1005{
1006 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
1007 if (!oname) {
1008 *result = NULL;
1009 return -1;
1010 }
1011 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +09001012}
1013
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001014int
Fred Drake100814d2000-07-09 15:48:49 +00001015PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001016{
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001017 PyObject *res;
1018 if (_PyObject_LookupAttr(v, name, &res) < 0) {
1019 PyErr_Clear();
1020 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001022 if (res == NULL) {
1023 return 0;
1024 }
1025 Py_DECREF(res);
1026 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001027}
1028
1029int
Fred Drake100814d2000-07-09 15:48:49 +00001030PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 PyTypeObject *tp = Py_TYPE(v);
1033 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 if (!PyUnicode_Check(name)) {
1036 PyErr_Format(PyExc_TypeError,
1037 "attribute name must be string, not '%.200s'",
1038 name->ob_type->tp_name);
1039 return -1;
1040 }
1041 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyUnicode_InternInPlace(&name);
1044 if (tp->tp_setattro != NULL) {
1045 err = (*tp->tp_setattro)(v, name, value);
1046 Py_DECREF(name);
1047 return err;
1048 }
1049 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001050 const char *name_str = PyUnicode_AsUTF8(name);
Zackery Spytze0dcb852019-04-28 06:58:52 -06001051 if (name_str == NULL) {
1052 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 return -1;
Zackery Spytze0dcb852019-04-28 06:58:52 -06001054 }
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001055 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 Py_DECREF(name);
1057 return err;
1058 }
1059 Py_DECREF(name);
Victor Stinner24702042018-10-26 17:16:37 +02001060 _PyObject_ASSERT(name, name->ob_refcnt >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1062 PyErr_Format(PyExc_TypeError,
1063 "'%.100s' object has no attributes "
1064 "(%s .%U)",
1065 tp->tp_name,
1066 value==NULL ? "del" : "assign to",
1067 name);
1068 else
1069 PyErr_Format(PyExc_TypeError,
1070 "'%.100s' object has only read-only attributes "
1071 "(%s .%U)",
1072 tp->tp_name,
1073 value==NULL ? "del" : "assign to",
1074 name);
1075 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076}
1077
1078/* Helper to get a pointer to an object's __dict__ slot, if any */
1079
1080PyObject **
1081_PyObject_GetDictPtr(PyObject *obj)
1082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 Py_ssize_t dictoffset;
1084 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 dictoffset = tp->tp_dictoffset;
1087 if (dictoffset == 0)
1088 return NULL;
1089 if (dictoffset < 0) {
1090 Py_ssize_t tsize;
1091 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 tsize = ((PyVarObject *)obj)->ob_size;
1094 if (tsize < 0)
1095 tsize = -tsize;
1096 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001099 _PyObject_ASSERT(obj, dictoffset > 0);
1100 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 }
1102 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001103}
1104
Tim Peters6d6c1a32001-08-02 04:15:00 +00001105PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001106PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 Py_INCREF(obj);
1109 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001110}
1111
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001112/* Helper used when the __next__ method is removed from a type:
1113 tp_iternext is never NULL and can be safely called without checking
1114 on every iteration.
1115 */
1116
1117PyObject *
1118_PyObject_NextNotImplemented(PyObject *self)
1119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyErr_Format(PyExc_TypeError,
1121 "'%.200s' object is not iterable",
1122 Py_TYPE(self)->tp_name);
1123 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001124}
1125
Yury Selivanovf2392132016-12-13 19:03:51 -05001126
1127/* Specialized version of _PyObject_GenericGetAttrWithDict
1128 specifically for the LOAD_METHOD opcode.
1129
1130 Return 1 if a method is found, 0 if it's a regular attribute
1131 from __dict__ or something returned by using a descriptor
1132 protocol.
1133
1134 `method` will point to the resolved attribute or NULL. In the
1135 latter case, an error will be set.
1136*/
1137int
1138_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1139{
1140 PyTypeObject *tp = Py_TYPE(obj);
1141 PyObject *descr;
1142 descrgetfunc f = NULL;
1143 PyObject **dictptr, *dict;
1144 PyObject *attr;
1145 int meth_found = 0;
1146
1147 assert(*method == NULL);
1148
1149 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1150 || !PyUnicode_Check(name)) {
1151 *method = PyObject_GetAttr(obj, name);
1152 return 0;
1153 }
1154
1155 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1156 return 0;
1157
1158 descr = _PyType_Lookup(tp, name);
1159 if (descr != NULL) {
1160 Py_INCREF(descr);
Jeroen Demeyereb65e242019-05-28 14:42:53 +02001161 if (PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001162 meth_found = 1;
1163 } else {
1164 f = descr->ob_type->tp_descr_get;
1165 if (f != NULL && PyDescr_IsData(descr)) {
1166 *method = f(descr, obj, (PyObject *)obj->ob_type);
1167 Py_DECREF(descr);
1168 return 0;
1169 }
1170 }
1171 }
1172
1173 dictptr = _PyObject_GetDictPtr(obj);
1174 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1175 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001176 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001177 if (attr != NULL) {
1178 Py_INCREF(attr);
1179 *method = attr;
1180 Py_DECREF(dict);
1181 Py_XDECREF(descr);
1182 return 0;
1183 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001184 else {
1185 Py_DECREF(dict);
1186 if (PyErr_Occurred()) {
1187 Py_XDECREF(descr);
1188 return 0;
1189 }
1190 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001191 }
1192
1193 if (meth_found) {
1194 *method = descr;
1195 return 1;
1196 }
1197
1198 if (f != NULL) {
1199 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1200 Py_DECREF(descr);
1201 return 0;
1202 }
1203
1204 if (descr != NULL) {
1205 *method = descr;
1206 return 0;
1207 }
1208
1209 PyErr_Format(PyExc_AttributeError,
1210 "'%.50s' object has no attribute '%U'",
1211 tp->tp_name, name);
1212 return 0;
1213}
1214
1215/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001216
Raymond Hettinger01538262003-03-17 08:24:35 +00001217PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001218_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1219 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001220{
Yury Selivanovf2392132016-12-13 19:03:51 -05001221 /* Make sure the logic of _PyObject_GetMethod is in sync with
1222 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001223
1224 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001225 */
1226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 PyTypeObject *tp = Py_TYPE(obj);
1228 PyObject *descr = NULL;
1229 PyObject *res = NULL;
1230 descrgetfunc f;
1231 Py_ssize_t dictoffset;
1232 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (!PyUnicode_Check(name)){
1235 PyErr_Format(PyExc_TypeError,
1236 "attribute name must be string, not '%.200s'",
1237 name->ob_type->tp_name);
1238 return NULL;
1239 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001240 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (tp->tp_dict == NULL) {
1243 if (PyType_Ready(tp) < 0)
1244 goto done;
1245 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 f = NULL;
1250 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001251 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 f = descr->ob_type->tp_descr_get;
1253 if (f != NULL && PyDescr_IsData(descr)) {
1254 res = f(descr, obj, (PyObject *)obj->ob_type);
INADA Naoki378edee2018-01-16 20:52:41 +09001255 if (res == NULL && suppress &&
1256 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1257 PyErr_Clear();
1258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 goto done;
1260 }
1261 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001262
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001263 if (dict == NULL) {
1264 /* Inline _PyObject_GetDictPtr */
1265 dictoffset = tp->tp_dictoffset;
1266 if (dictoffset != 0) {
1267 if (dictoffset < 0) {
1268 Py_ssize_t tsize;
1269 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001270
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001271 tsize = ((PyVarObject *)obj)->ob_size;
1272 if (tsize < 0)
1273 tsize = -tsize;
1274 size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001275 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001276
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001277 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001278 _PyObject_ASSERT(obj, dictoffset > 0);
1279 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001281 dictptr = (PyObject **) ((char *)obj + dictoffset);
1282 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 }
1284 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001285 if (dict != NULL) {
1286 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001287 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001288 if (res != NULL) {
1289 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001290 Py_DECREF(dict);
1291 goto done;
1292 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001293 else {
1294 Py_DECREF(dict);
1295 if (PyErr_Occurred()) {
1296 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1297 PyErr_Clear();
1298 }
1299 else {
1300 goto done;
1301 }
1302 }
1303 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001304 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (f != NULL) {
1307 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001308 if (res == NULL && suppress &&
1309 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1310 PyErr_Clear();
1311 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 goto done;
1313 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 if (descr != NULL) {
1316 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001317 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 goto done;
1319 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001320
INADA Naoki378edee2018-01-16 20:52:41 +09001321 if (!suppress) {
1322 PyErr_Format(PyExc_AttributeError,
1323 "'%.50s' object has no attribute '%U'",
1324 tp->tp_name, name);
1325 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001326 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001327 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 Py_DECREF(name);
1329 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001330}
1331
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001332PyObject *
1333PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1334{
INADA Naoki378edee2018-01-16 20:52:41 +09001335 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001336}
1337
Tim Peters6d6c1a32001-08-02 04:15:00 +00001338int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001339_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1340 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 PyTypeObject *tp = Py_TYPE(obj);
1343 PyObject *descr;
1344 descrsetfunc f;
1345 PyObject **dictptr;
1346 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (!PyUnicode_Check(name)){
1349 PyErr_Format(PyExc_TypeError,
1350 "attribute name must be string, not '%.200s'",
1351 name->ob_type->tp_name);
1352 return -1;
1353 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001354
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001355 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1356 return -1;
1357
1358 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001363 Py_INCREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 f = descr->ob_type->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001365 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 res = f(descr, obj, value);
1367 goto done;
1368 }
1369 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001370
Steve Dowerb82e17e2019-05-23 08:45:22 -07001371 /* XXX [Steve Dower] These are really noisy - worth it? */
1372 /*if (PyType_Check(obj) || PyModule_Check(obj)) {
1373 if (value && PySys_Audit("object.__setattr__", "OOO", obj, name, value) < 0)
1374 return -1;
1375 if (!value && PySys_Audit("object.__delattr__", "OO", obj, name) < 0)
1376 return -1;
1377 }*/
1378
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001379 if (dict == NULL) {
1380 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001381 if (dictptr == NULL) {
1382 if (descr == NULL) {
1383 PyErr_Format(PyExc_AttributeError,
1384 "'%.100s' object has no attribute '%U'",
1385 tp->tp_name, name);
1386 }
1387 else {
1388 PyErr_Format(PyExc_AttributeError,
1389 "'%.50s' object attribute '%U' is read-only",
1390 tp->tp_name, name);
1391 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001392 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001394 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001395 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001396 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001397 Py_INCREF(dict);
1398 if (value == NULL)
1399 res = PyDict_DelItem(dict, name);
1400 else
1401 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001402 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001404 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1405 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001407 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001408 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 Py_DECREF(name);
1410 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001411}
1412
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001413int
1414PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1415{
1416 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1417}
1418
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001419int
1420PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1421{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001422 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001423 if (dictptr == NULL) {
1424 PyErr_SetString(PyExc_AttributeError,
1425 "This object has no __dict__");
1426 return -1;
1427 }
1428 if (value == NULL) {
1429 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1430 return -1;
1431 }
1432 if (!PyDict_Check(value)) {
1433 PyErr_Format(PyExc_TypeError,
1434 "__dict__ must be set to a dictionary, "
1435 "not a '%.200s'", Py_TYPE(value)->tp_name);
1436 return -1;
1437 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001438 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001439 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001440 return 0;
1441}
1442
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001443
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001444/* Test a value used as condition, e.g., in a for or if statement.
1445 Return -1 if an error occurred */
1446
1447int
Fred Drake100814d2000-07-09 15:48:49 +00001448PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 Py_ssize_t res;
1451 if (v == Py_True)
1452 return 1;
1453 if (v == Py_False)
1454 return 0;
1455 if (v == Py_None)
1456 return 0;
1457 else if (v->ob_type->tp_as_number != NULL &&
1458 v->ob_type->tp_as_number->nb_bool != NULL)
1459 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1460 else if (v->ob_type->tp_as_mapping != NULL &&
1461 v->ob_type->tp_as_mapping->mp_length != NULL)
1462 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1463 else if (v->ob_type->tp_as_sequence != NULL &&
1464 v->ob_type->tp_as_sequence->sq_length != NULL)
1465 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1466 else
1467 return 1;
1468 /* if it is negative, it should be either -1 or -2 */
1469 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001470}
1471
Tim Peters803526b2002-07-07 05:13:56 +00001472/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001473 Return -1 if an error occurred */
1474
1475int
Fred Drake100814d2000-07-09 15:48:49 +00001476PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 int res;
1479 res = PyObject_IsTrue(v);
1480 if (res < 0)
1481 return res;
1482 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001483}
1484
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001485/* Test whether an object can be called */
1486
1487int
Fred Drake100814d2000-07-09 15:48:49 +00001488PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (x == NULL)
1491 return 0;
1492 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001493}
1494
Tim Peters7eea37e2001-09-04 22:08:56 +00001495
Georg Brandle32b4222007-03-10 22:13:27 +00001496/* Helper for PyObject_Dir without arguments: returns the local scope. */
1497static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001498_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001501 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001502
Victor Stinner41bb43a2013-10-29 01:19:37 +01001503 locals = PyEval_GetLocals();
1504 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 names = PyMapping_Keys(locals);
1508 if (!names)
1509 return NULL;
1510 if (!PyList_Check(names)) {
1511 PyErr_Format(PyExc_TypeError,
1512 "dir(): expected keys() of locals to be a list, "
1513 "not '%.200s'", Py_TYPE(names)->tp_name);
1514 Py_DECREF(names);
1515 return NULL;
1516 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001517 if (PyList_Sort(names)) {
1518 Py_DECREF(names);
1519 return NULL;
1520 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 /* the locals don't need to be DECREF'd */
1522 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001523}
1524
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001525/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001526static PyObject *
1527_dir_object(PyObject *obj)
1528{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001529 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001530 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001531
Victor Stinner24702042018-10-26 17:16:37 +02001532 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001534 if (!PyErr_Occurred())
1535 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1536 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001538 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001539 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001540 Py_DECREF(dirfunc);
1541 if (result == NULL)
1542 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001543 /* return sorted(result) */
1544 sorted = PySequence_List(result);
1545 Py_DECREF(result);
1546 if (sorted == NULL)
1547 return NULL;
1548 if (PyList_Sort(sorted)) {
1549 Py_DECREF(sorted);
1550 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001552 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001553}
1554
1555/* Implementation of dir() -- if obj is NULL, returns the names in the current
1556 (local) scope. Otherwise, performs introspection of the object: returns a
1557 sorted list of attribute names (supposedly) accessible from the object
1558*/
1559PyObject *
1560PyObject_Dir(PyObject *obj)
1561{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001562 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001563}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001564
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001565/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001566None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001567There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001568so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001569*/
1570
Guido van Rossum0c182a11992-03-27 17:26:13 +00001571/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001572static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001573none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001576}
1577
Barry Warsaw9bf16442001-01-23 16:24:35 +00001578/* ARGUSED */
1579static void
Tim Peters803526b2002-07-07 05:13:56 +00001580none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 /* This should never get called, but we also don't want to SEGV if
1583 * we accidentally decref None out of existence.
1584 */
1585 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001586}
1587
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001588static PyObject *
1589none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1590{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001591 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001592 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1593 return NULL;
1594 }
1595 Py_RETURN_NONE;
1596}
1597
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001598static int
1599none_bool(PyObject *v)
1600{
1601 return 0;
1602}
1603
1604static PyNumberMethods none_as_number = {
1605 0, /* nb_add */
1606 0, /* nb_subtract */
1607 0, /* nb_multiply */
1608 0, /* nb_remainder */
1609 0, /* nb_divmod */
1610 0, /* nb_power */
1611 0, /* nb_negative */
1612 0, /* nb_positive */
1613 0, /* nb_absolute */
1614 (inquiry)none_bool, /* nb_bool */
1615 0, /* nb_invert */
1616 0, /* nb_lshift */
1617 0, /* nb_rshift */
1618 0, /* nb_and */
1619 0, /* nb_xor */
1620 0, /* nb_or */
1621 0, /* nb_int */
1622 0, /* nb_reserved */
1623 0, /* nb_float */
1624 0, /* nb_inplace_add */
1625 0, /* nb_inplace_subtract */
1626 0, /* nb_inplace_multiply */
1627 0, /* nb_inplace_remainder */
1628 0, /* nb_inplace_power */
1629 0, /* nb_inplace_lshift */
1630 0, /* nb_inplace_rshift */
1631 0, /* nb_inplace_and */
1632 0, /* nb_inplace_xor */
1633 0, /* nb_inplace_or */
1634 0, /* nb_floor_divide */
1635 0, /* nb_true_divide */
1636 0, /* nb_inplace_floor_divide */
1637 0, /* nb_inplace_true_divide */
1638 0, /* nb_index */
1639};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001640
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001641PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1643 "NoneType",
1644 0,
1645 0,
1646 none_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001647 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 0, /*tp_getattr*/
1649 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001650 0, /*tp_as_async*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001652 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 0, /*tp_as_sequence*/
1654 0, /*tp_as_mapping*/
1655 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001656 0, /*tp_call */
1657 0, /*tp_str */
1658 0, /*tp_getattro */
1659 0, /*tp_setattro */
1660 0, /*tp_as_buffer */
1661 Py_TPFLAGS_DEFAULT, /*tp_flags */
1662 0, /*tp_doc */
1663 0, /*tp_traverse */
1664 0, /*tp_clear */
1665 0, /*tp_richcompare */
1666 0, /*tp_weaklistoffset */
1667 0, /*tp_iter */
1668 0, /*tp_iternext */
1669 0, /*tp_methods */
1670 0, /*tp_members */
1671 0, /*tp_getset */
1672 0, /*tp_base */
1673 0, /*tp_dict */
1674 0, /*tp_descr_get */
1675 0, /*tp_descr_set */
1676 0, /*tp_dictoffset */
1677 0, /*tp_init */
1678 0, /*tp_alloc */
1679 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001680};
1681
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001682PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001683 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001684 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001685};
1686
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001687/* NotImplemented is an object that can be used to signal that an
1688 operation is not implemented for the given type combination. */
1689
1690static PyObject *
1691NotImplemented_repr(PyObject *op)
1692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001694}
1695
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001696static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301697NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001698{
1699 return PyUnicode_FromString("NotImplemented");
1700}
1701
1702static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301703 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001704 {NULL, NULL}
1705};
1706
1707static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001708notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1709{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001710 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001711 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1712 return NULL;
1713 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001714 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001715}
1716
Armin Ronacher226b1db2012-10-06 14:28:58 +02001717static void
1718notimplemented_dealloc(PyObject* ignore)
1719{
1720 /* This should never get called, but we also don't want to SEGV if
1721 * we accidentally decref NotImplemented out of existence.
1722 */
1723 Py_FatalError("deallocating NotImplemented");
1724}
1725
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001726PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1728 "NotImplementedType",
1729 0,
1730 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001731 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001732 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 0, /*tp_getattr*/
1734 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001735 0, /*tp_as_async*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 NotImplemented_repr, /*tp_repr*/
1737 0, /*tp_as_number*/
1738 0, /*tp_as_sequence*/
1739 0, /*tp_as_mapping*/
1740 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001741 0, /*tp_call */
1742 0, /*tp_str */
1743 0, /*tp_getattro */
1744 0, /*tp_setattro */
1745 0, /*tp_as_buffer */
1746 Py_TPFLAGS_DEFAULT, /*tp_flags */
1747 0, /*tp_doc */
1748 0, /*tp_traverse */
1749 0, /*tp_clear */
1750 0, /*tp_richcompare */
1751 0, /*tp_weaklistoffset */
1752 0, /*tp_iter */
1753 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001754 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001755 0, /*tp_members */
1756 0, /*tp_getset */
1757 0, /*tp_base */
1758 0, /*tp_dict */
1759 0, /*tp_descr_get */
1760 0, /*tp_descr_set */
1761 0, /*tp_dictoffset */
1762 0, /*tp_init */
1763 0, /*tp_alloc */
1764 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001765};
1766
1767PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001769 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001770};
1771
Victor Stinner331a6a52019-05-27 16:39:22 +02001772PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01001773_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001774{
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001775#define INIT_TYPE(TYPE, NAME) \
1776 do { \
1777 if (PyType_Ready(TYPE) < 0) { \
Victor Stinner331a6a52019-05-27 16:39:22 +02001778 return _PyStatus_ERR("Can't initialize " NAME " type"); \
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001779 } \
1780 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001781
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001782 INIT_TYPE(&PyBaseObject_Type, "object");
1783 INIT_TYPE(&PyType_Type, "type");
1784 INIT_TYPE(&_PyWeakref_RefType, "weakref");
1785 INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
1786 INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
1787 INIT_TYPE(&PyLong_Type, "int");
1788 INIT_TYPE(&PyBool_Type, "bool");
1789 INIT_TYPE(&PyByteArray_Type, "bytearray");
1790 INIT_TYPE(&PyBytes_Type, "str");
1791 INIT_TYPE(&PyList_Type, "list");
1792 INIT_TYPE(&_PyNone_Type, "None");
1793 INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
1794 INIT_TYPE(&PyTraceBack_Type, "traceback");
1795 INIT_TYPE(&PySuper_Type, "super");
1796 INIT_TYPE(&PyRange_Type, "range");
1797 INIT_TYPE(&PyDict_Type, "dict");
1798 INIT_TYPE(&PyDictKeys_Type, "dict keys");
1799 INIT_TYPE(&PyDictValues_Type, "dict values");
1800 INIT_TYPE(&PyDictItems_Type, "dict items");
1801 INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
1802 INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
1803 INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
1804 INIT_TYPE(&PyODict_Type, "OrderedDict");
1805 INIT_TYPE(&PyODictKeys_Type, "odict_keys");
1806 INIT_TYPE(&PyODictItems_Type, "odict_items");
1807 INIT_TYPE(&PyODictValues_Type, "odict_values");
1808 INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
1809 INIT_TYPE(&PySet_Type, "set");
1810 INIT_TYPE(&PyUnicode_Type, "str");
1811 INIT_TYPE(&PySlice_Type, "slice");
1812 INIT_TYPE(&PyStaticMethod_Type, "static method");
1813 INIT_TYPE(&PyComplex_Type, "complex");
1814 INIT_TYPE(&PyFloat_Type, "float");
1815 INIT_TYPE(&PyFrozenSet_Type, "frozenset");
1816 INIT_TYPE(&PyProperty_Type, "property");
1817 INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
1818 INIT_TYPE(&PyMemoryView_Type, "memoryview");
1819 INIT_TYPE(&PyTuple_Type, "tuple");
1820 INIT_TYPE(&PyEnum_Type, "enumerate");
1821 INIT_TYPE(&PyReversed_Type, "reversed");
1822 INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
1823 INIT_TYPE(&PyCode_Type, "code");
1824 INIT_TYPE(&PyFrame_Type, "frame");
1825 INIT_TYPE(&PyCFunction_Type, "builtin function");
1826 INIT_TYPE(&PyMethod_Type, "method");
1827 INIT_TYPE(&PyFunction_Type, "function");
1828 INIT_TYPE(&PyDictProxy_Type, "dict proxy");
1829 INIT_TYPE(&PyGen_Type, "generator");
1830 INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
1831 INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
1832 INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
1833 INIT_TYPE(&PyEllipsis_Type, "ellipsis");
1834 INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
1835 INIT_TYPE(&_PyNamespace_Type, "namespace");
1836 INIT_TYPE(&PyCapsule_Type, "capsule");
1837 INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
1838 INIT_TYPE(&PyCell_Type, "cell");
1839 INIT_TYPE(&PyInstanceMethod_Type, "instance method");
1840 INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
1841 INIT_TYPE(&PyMethodDescr_Type, "method descr");
1842 INIT_TYPE(&PyCallIter_Type, "call iter");
1843 INIT_TYPE(&PySeqIter_Type, "sequence iterator");
Antoine Pitrou91f43802019-05-26 17:10:09 +02001844 INIT_TYPE(&PyPickleBuffer_Type, "pickle.PickleBuffer");
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001845 INIT_TYPE(&PyCoro_Type, "coroutine");
1846 INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
Eric Snowc11183c2019-03-15 16:35:46 -06001847 INIT_TYPE(&_PyInterpreterID_Type, "interpreter ID");
Victor Stinner331a6a52019-05-27 16:39:22 +02001848 return _PyStatus_OK();
Guido van Rossumba21a492001-08-16 08:17:26 +00001849
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001850#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001851}
1852
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001853
Guido van Rossum84a90321996-05-22 16:34:47 +00001854#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001855
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001856void
Fred Drake100814d2000-07-09 15:48:49 +00001857_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858{
Victor Stinner9e00e802018-10-25 13:31:16 +02001859 if (_Py_tracemalloc_config.tracing) {
1860 _PyTraceMalloc_NewReference(op);
1861 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 _Py_INC_REFTOTAL;
1863 op->ob_refcnt = 1;
1864 _Py_AddToAllObjects(op, 1);
1865 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001866}
1867
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001868void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001869_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001870{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001871#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001872 PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001873#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (op->ob_refcnt < 0)
1875 Py_FatalError("UNREF negative refcnt");
1876 if (op == &refchain ||
1877 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1878 fprintf(stderr, "* ob\n");
1879 _PyObject_Dump(op);
1880 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1881 _PyObject_Dump(op->_ob_prev->_ob_next);
1882 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1883 _PyObject_Dump(op->_ob_next->_ob_prev);
1884 Py_FatalError("UNREF invalid object");
1885 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001886#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1888 if (p == op)
1889 break;
1890 }
1891 if (p == &refchain) /* Not found */
1892 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001893#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 op->_ob_next->_ob_prev = op->_ob_prev;
1895 op->_ob_prev->_ob_next = op->_ob_next;
1896 op->_ob_next = op->_ob_prev = NULL;
1897 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001898}
1899
Tim Peters269b2a62003-04-17 19:52:29 +00001900/* Print all live objects. Because PyObject_Print is called, the
1901 * interpreter must be in a healthy state.
1902 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001903void
Fred Drake100814d2000-07-09 15:48:49 +00001904_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 PyObject *op;
1907 fprintf(fp, "Remaining objects:\n");
1908 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001909 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", (void *)op, op->ob_refcnt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 if (PyObject_Print(op, fp, 0) != 0)
1911 PyErr_Clear();
1912 putc('\n', fp);
1913 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001914}
1915
Tim Peters269b2a62003-04-17 19:52:29 +00001916/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1917 * doesn't make any calls to the Python C API, so is always safe to call.
1918 */
1919void
1920_Py_PrintReferenceAddresses(FILE *fp)
1921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyObject *op;
1923 fprintf(fp, "Remaining object addresses:\n");
1924 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001925 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", (void *)op,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001927}
1928
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001929PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001930_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 int i, n;
1933 PyObject *t = NULL;
1934 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1937 return NULL;
1938 op = refchain._ob_next;
1939 res = PyList_New(0);
1940 if (res == NULL)
1941 return NULL;
1942 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1943 while (op == self || op == args || op == res || op == t ||
1944 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1945 op = op->_ob_next;
1946 if (op == &refchain)
1947 return res;
1948 }
1949 if (PyList_Append(res, op) < 0) {
1950 Py_DECREF(res);
1951 return NULL;
1952 }
1953 op = op->_ob_next;
1954 }
1955 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001956}
1957
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001958#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001959
Benjamin Petersonb173f782009-05-05 22:31:58 +00001960
Guido van Rossum84a90321996-05-22 16:34:47 +00001961/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001962Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001963
1964
David Malcolm49526f42012-06-22 14:55:41 -04001965void
1966_PyObject_DebugTypeStats(FILE *out)
1967{
David Malcolm49526f42012-06-22 14:55:41 -04001968 _PyDict_DebugMallocStats(out);
1969 _PyFloat_DebugMallocStats(out);
1970 _PyFrame_DebugMallocStats(out);
1971 _PyList_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001972 _PyTuple_DebugMallocStats(out);
1973}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001974
Guido van Rossum86610361998-04-10 22:32:46 +00001975/* These methods are used to control infinite recursion in repr, str, print,
1976 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00001977 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00001978 Py_ReprLeave() to avoid infinite recursion.
1979
1980 Py_ReprEnter() returns 0 the first time it is called for a particular
1981 object and 1 every time thereafter. It returns -1 if an exception
1982 occurred. Py_ReprLeave() has no return value.
1983
1984 See dictobject.c and listobject.c for examples of use.
1985*/
1986
Guido van Rossum86610361998-04-10 22:32:46 +00001987int
Fred Drake100814d2000-07-09 15:48:49 +00001988Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 PyObject *dict;
1991 PyObject *list;
1992 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02001995 /* Ignore a missing thread-state, so that this function can be called
1996 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (dict == NULL)
1998 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001999 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002001 if (PyErr_Occurred()) {
2002 return -1;
2003 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 list = PyList_New(0);
2005 if (list == NULL)
2006 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01002007 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 return -1;
2009 Py_DECREF(list);
2010 }
2011 i = PyList_GET_SIZE(list);
2012 while (--i >= 0) {
2013 if (PyList_GET_ITEM(list, i) == obj)
2014 return 1;
2015 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02002016 if (PyList_Append(list, obj) < 0)
2017 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002019}
2020
2021void
Fred Drake100814d2000-07-09 15:48:49 +00002022Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyObject *dict;
2025 PyObject *list;
2026 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002027 PyObject *error_type, *error_value, *error_traceback;
2028
2029 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 dict = PyThreadState_GetDict();
2032 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002033 goto finally;
2034
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002035 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002037 goto finally;
2038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 i = PyList_GET_SIZE(list);
2040 /* Count backwards because we always expect obj to be list[-1] */
2041 while (--i >= 0) {
2042 if (PyList_GET_ITEM(list, i) == obj) {
2043 PyList_SetSlice(list, i, i + 1, NULL);
2044 break;
2045 }
2046 }
Victor Stinner1b634932013-07-16 22:24:44 +02002047
2048finally:
2049 /* ignore exceptions because there is no way to report them. */
2050 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002051}
Guido van Rossumd724b232000-03-13 16:01:29 +00002052
Tim Peters803526b2002-07-07 05:13:56 +00002053/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002054
Tim Peters803526b2002-07-07 05:13:56 +00002055/* Add op to the _PyTrash_delete_later list. Called when the current
2056 * call-stack depth gets large. op must be a currently untracked gc'ed
2057 * object, with refcount 0. Py_DECREF must already have been called on it.
2058 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002059void
Fred Drake100814d2000-07-09 15:48:49 +00002060_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002061{
Victor Stinner24702042018-10-26 17:16:37 +02002062 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2063 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2064 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002065 _PyGCHead_SET_PREV(_Py_AS_GC(op), _PyRuntime.gc.trash_delete_later);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002066 _PyRuntime.gc.trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002067}
2068
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002069/* The equivalent API, using per-thread state recursion info */
2070void
2071_PyTrash_thread_deposit_object(PyObject *op)
2072{
Victor Stinner50b48572018-11-01 01:51:40 +01002073 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002074 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2075 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
2076 _PyObject_ASSERT(op, op->ob_refcnt == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002077 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002078 tstate->trash_delete_later = op;
2079}
2080
Min ho Kimc4cacc82019-07-31 08:16:13 +10002081/* Deallocate all the objects in the _PyTrash_delete_later list. Called when
Tim Peters803526b2002-07-07 05:13:56 +00002082 * the call-stack unwinds again.
2083 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002084void
Fred Drake100814d2000-07-09 15:48:49 +00002085_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002086{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002087 while (_PyRuntime.gc.trash_delete_later) {
2088 PyObject *op = _PyRuntime.gc.trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002090
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002091 _PyRuntime.gc.trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002092 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 /* Call the deallocator directly. This used to try to
2095 * fool Py_DECREF into calling it indirectly, but
2096 * Py_DECREF was already called on this object, and in
2097 * assorted non-release builds calling Py_DECREF again ends
2098 * up distorting allocation statistics.
2099 */
Victor Stinner24702042018-10-26 17:16:37 +02002100 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002101 ++_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 (*dealloc)(op);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002103 --_PyRuntime.gc.trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002105}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002106
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002107/* The equivalent API, using per-thread state recursion info */
2108void
2109_PyTrash_thread_destroy_chain(void)
2110{
Victor Stinner50b48572018-11-01 01:51:40 +01002111 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002112 /* We need to increase trash_delete_nesting here, otherwise,
2113 _PyTrash_thread_destroy_chain will be called recursively
2114 and then possibly crash. An example that may crash without
2115 increase:
2116 N = 500000 # need to be large enough
2117 ob = object()
2118 tups = [(ob,) for i in range(N)]
2119 for i in range(49):
2120 tups = [(tup,) for tup in tups]
2121 del tups
2122 */
2123 assert(tstate->trash_delete_nesting == 0);
2124 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002125 while (tstate->trash_delete_later) {
2126 PyObject *op = tstate->trash_delete_later;
2127 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2128
2129 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002130 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002131
2132 /* Call the deallocator directly. This used to try to
2133 * fool Py_DECREF into calling it indirectly, but
2134 * Py_DECREF was already called on this object, and in
2135 * assorted non-release builds calling Py_DECREF again ends
2136 * up distorting allocation statistics.
2137 */
Victor Stinner24702042018-10-26 17:16:37 +02002138 _PyObject_ASSERT(op, op->ob_refcnt == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002139 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002140 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002141 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002142 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002143}
2144
Victor Stinner626bff82018-10-25 17:31:10 +02002145
2146void
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002147_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002148 const char *file, int line, const char *function)
2149{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002150 fprintf(stderr, "%s:%d: ", file, line);
2151 if (function) {
2152 fprintf(stderr, "%s: ", function);
2153 }
Victor Stinner626bff82018-10-25 17:31:10 +02002154 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002155
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002156 if (expr) {
2157 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002158 }
2159 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002160 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002161 }
2162 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002163
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002164 if (msg) {
2165 fprintf(stderr, ": %s", msg);
2166 }
2167 fprintf(stderr, "\n");
2168 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002169
Victor Stinner68762572019-10-07 18:42:01 +02002170 if (_PyObject_IsFreed(obj)) {
Victor Stinner626bff82018-10-25 17:31:10 +02002171 /* It seems like the object memory has been freed:
2172 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +02002173 fprintf(stderr, "<object at %p is freed>\n", obj);
Victor Stinner68762572019-10-07 18:42:01 +02002174 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002175 }
2176 else {
penguindustin96466302019-05-06 14:57:17 -04002177 /* Display the traceback where the object has been allocated.
Victor Stinner626bff82018-10-25 17:31:10 +02002178 Do it before dumping repr(obj), since repr() is more likely
2179 to crash than dumping the traceback. */
2180 void *ptr;
2181 PyTypeObject *type = Py_TYPE(obj);
2182 if (PyType_IS_GC(type)) {
2183 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2184 }
2185 else {
2186 ptr = (void *)obj;
2187 }
2188 _PyMem_DumpTraceback(fileno(stderr), ptr);
2189
2190 /* This might succeed or fail, but we're about to abort, so at least
2191 try to provide any extra info we can: */
2192 _PyObject_Dump(obj);
Victor Stinner77753492019-10-07 23:44:05 +02002193
2194 fprintf(stderr, "\n");
2195 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002196 }
Victor Stinner626bff82018-10-25 17:31:10 +02002197
2198 Py_FatalError("_PyObject_AssertFailed");
2199}
2200
Victor Stinner3c09dca2018-10-30 14:48:26 +01002201
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002202#undef _Py_Dealloc
Victor Stinner3c09dca2018-10-30 14:48:26 +01002203
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002204void
2205_Py_Dealloc(PyObject *op)
2206{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002207 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2208#ifdef Py_TRACE_REFS
2209 _Py_ForgetReference(op);
2210#else
2211 _Py_INC_TPFREES(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002212#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002213 (*dealloc)(op);
2214}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002215
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002216#ifdef __cplusplus
2217}
2218#endif