blob: ef4ba997de427334c24ebbc67b570067fc4b6eeb [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 Stinner224481a2020-03-13 10:19:38 +01005#include "pycore_ceval.h" // _Py_EnterRecursiveCall()
Victor Stinnerbe434dc2019-11-05 00:51:22 +01006#include "pycore_context.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02007#include "pycore_initconfig.h"
Victor Stinner0fc91ee2019-04-12 21:51:34 +02008#include "pycore_object.h"
Victor Stinnerbe434dc2019-11-05 00:51:22 +01009#include "pycore_pyerrors.h"
Victor Stinner7a1f6c22020-01-30 09:02:14 +010010#include "pycore_pylifecycle.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010011#include "pycore_pystate.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +000012#include "frameobject.h"
Eric Snowc11183c2019-03-15 16:35:46 -060013#include "interpreteridobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015#ifdef __cplusplus
16extern "C" {
17#endif
18
Victor Stinner626bff82018-10-25 17:31:10 +020019/* Defined in tracemalloc.c */
20extern void _PyMem_DumpTraceback(int fd, const void *ptr);
21
Victor Stinnerbd303c12013-11-07 23:07:29 +010022_Py_IDENTIFIER(Py_Repr);
23_Py_IDENTIFIER(__bytes__);
24_Py_IDENTIFIER(__dir__);
25_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010026
Victor Stinner0fc91ee2019-04-12 21:51:34 +020027
28int
29_PyObject_CheckConsistency(PyObject *op, int check_content)
30{
Victor Stinner68762572019-10-07 18:42:01 +020031#define CHECK(expr) \
32 do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
Victor Stinner0fc91ee2019-04-12 21:51:34 +020033
Victor Stinner68762572019-10-07 18:42:01 +020034 CHECK(!_PyObject_IsFreed(op));
35 CHECK(Py_REFCNT(op) >= 1);
36
Victor Stinner58ac7002020-02-07 03:04:21 +010037 _PyType_CheckConsistency(Py_TYPE(op));
Victor Stinner0fc91ee2019-04-12 21:51:34 +020038
39 if (PyUnicode_Check(op)) {
40 _PyUnicode_CheckConsistency(op, check_content);
41 }
42 else if (PyDict_Check(op)) {
43 _PyDict_CheckConsistency(op, check_content);
44 }
45 return 1;
Victor Stinner68762572019-10-07 18:42:01 +020046
47#undef CHECK
Victor Stinner0fc91ee2019-04-12 21:51:34 +020048}
49
50
Tim Peters34592512002-07-11 06:23:50 +000051#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000052Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000053
54Py_ssize_t
55_Py_GetRefTotal(void)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 PyObject *o;
58 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020059 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 if (o != NULL)
Victor Stinnera93c51e2020-02-07 00:38:59 +010061 total -= Py_REFCNT(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000063}
Nick Coghland6009512014-11-20 21:39:37 +100064
65void
66_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070067 fprintf(stderr,
68 "[%" PY_FORMAT_SIZE_T "d refs, "
69 "%" PY_FORMAT_SIZE_T "d blocks]\n",
70 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100071}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000072#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073
Guido van Rossum3f5da241990-12-20 15:06:42 +000074/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
75 These are used by the individual routines for object creation.
76 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077
Tim Peters78be7992003-03-23 02:51:01 +000078#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000079/* Head of circular doubly-linked list of all objects. These are linked
80 * together via the _ob_prev and _ob_next members of a PyObject, which
81 * exist only in a Py_TRACE_REFS build.
82 */
Tim Peters78be7992003-03-23 02:51:01 +000083static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000084
Tim Peters7571a0f2003-03-23 17:52:28 +000085/* Insert op at the front of the list of all objects. If force is true,
86 * op is added even if _ob_prev and _ob_next are non-NULL already. If
87 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
88 * force should be true if and only if op points to freshly allocated,
89 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000090 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000091 * Note that objects are normally added to the list via _Py_NewReference,
92 * which is called by PyObject_Init. Not all objects are initialized that
93 * way, though; exceptions include statically allocated type objects, and
94 * statically allocated singletons (like Py_True and Py_None).
95 */
Victor Stinner58f4e1a2020-02-05 18:24:33 +010096void
Tim Peters7571a0f2003-03-23 17:52:28 +000097_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000098{
Tim Peters7571a0f2003-03-23 17:52:28 +000099#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (!force) {
101 /* If it's initialized memory, op must be in or out of
102 * the list unambiguously.
103 */
Victor Stinner24702042018-10-26 17:16:37 +0200104 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Tim Peters78be7992003-03-23 02:51:01 +0000106#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 if (force || op->_ob_prev == NULL) {
108 op->_ob_next = refchain._ob_next;
109 op->_ob_prev = &refchain;
110 refchain._ob_next->_ob_prev = op;
111 refchain._ob_next = op;
112 }
Tim Peters7571a0f2003-03-23 17:52:28 +0000113}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +0000115
Tim Peters7c321a82002-07-09 02:57:01 +0000116#ifdef Py_REF_DEBUG
117/* Log a fatal error; doesn't return. */
118void
Victor Stinner18618e652018-10-25 17:28:11 +0200119_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000120{
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100121 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200122 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000123}
124
125#endif /* Py_REF_DEBUG */
126
Thomas Heller1328b522004-04-22 17:23:49 +0000127void
128Py_IncRef(PyObject *o)
129{
130 Py_XINCREF(o);
131}
132
133void
134Py_DecRef(PyObject *o)
135{
136 Py_XDECREF(o);
137}
138
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000140PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141{
Victor Stinnerf58bd7c2020-02-05 13:12:19 +0100142 /* Any changes should be reflected in PyObject_INIT() macro */
143 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 return PyErr_NoMemory();
Victor Stinnerf58bd7c2020-02-05 13:12:19 +0100145 }
146
Victor Stinner1fb5a9f2020-03-06 15:55:14 +0100147 return PyObject_INIT(op, tp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148}
149
Guido van Rossumb18618d2000-05-03 23:44:39 +0000150PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000151PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000152{
Victor Stinnerf58bd7c2020-02-05 13:12:19 +0100153 /* Any changes should be reflected in PyObject_INIT_VAR() macro */
154 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 return (PyVarObject *) PyErr_NoMemory();
Victor Stinnerf58bd7c2020-02-05 13:12:19 +0100156 }
157
Victor Stinner1fb5a9f2020-03-06 15:55:14 +0100158 return PyObject_INIT_VAR(op, tp, size);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000159}
160
161PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000162_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000163{
Victor Stinner92055202020-04-08 00:38:15 +0200164 PyObject *op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
165 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 return PyErr_NoMemory();
Victor Stinner92055202020-04-08 00:38:15 +0200167 }
168 PyObject_INIT(op, tp);
169 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000170}
171
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000172PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000173_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PyVarObject *op;
176 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
177 op = (PyVarObject *) PyObject_MALLOC(size);
178 if (op == NULL)
179 return (PyVarObject *)PyErr_NoMemory();
180 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000181}
182
Antoine Pitrou796564c2013-07-30 19:59:21 +0200183void
184PyObject_CallFinalizer(PyObject *self)
185{
186 PyTypeObject *tp = Py_TYPE(self);
187
Antoine Pitrouada319b2019-05-29 22:12:38 +0200188 if (tp->tp_finalize == NULL)
Antoine Pitrou796564c2013-07-30 19:59:21 +0200189 return;
190 /* tp_finalize should only be called once. */
Victor Stinner45ec5b92020-04-08 01:42:27 +0200191 if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
Antoine Pitrou796564c2013-07-30 19:59:21 +0200192 return;
193
194 tp->tp_finalize(self);
Victor Stinner45ec5b92020-04-08 01:42:27 +0200195 if (_PyType_IS_GC(tp)) {
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900196 _PyGC_SET_FINALIZED(self);
197 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200198}
199
200int
201PyObject_CallFinalizerFromDealloc(PyObject *self)
202{
Victor Stinnera93c51e2020-02-07 00:38:59 +0100203 if (Py_REFCNT(self) != 0) {
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100204 _PyObject_ASSERT_FAILED_MSG(self,
205 "PyObject_CallFinalizerFromDealloc called "
206 "on object with a non-zero refcount");
207 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200208
209 /* Temporarily resurrect the object. */
Victor Stinnerc86a1122020-02-07 01:24:29 +0100210 Py_SET_REFCNT(self, 1);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200211
212 PyObject_CallFinalizer(self);
213
Victor Stinner24702042018-10-26 17:16:37 +0200214 _PyObject_ASSERT_WITH_MSG(self,
Victor Stinnera93c51e2020-02-07 00:38:59 +0100215 Py_REFCNT(self) > 0,
Victor Stinner24702042018-10-26 17:16:37 +0200216 "refcount is too small");
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100217
218 /* Undo the temporary resurrection; can't use DECREF here, it would
219 * cause a recursive call. */
Victor Stinnerc86a1122020-02-07 01:24:29 +0100220 Py_SET_REFCNT(self, Py_REFCNT(self) - 1);
221 if (Py_REFCNT(self) == 0) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200222 return 0; /* this is the normal path out */
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100223 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200224
225 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100226 * never happened. */
Victor Stinnera93c51e2020-02-07 00:38:59 +0100227 Py_ssize_t refcnt = Py_REFCNT(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200228 _Py_NewReference(self);
Victor Stinnerc86a1122020-02-07 01:24:29 +0100229 Py_SET_REFCNT(self, refcnt);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200230
Victor Stinner24702042018-10-26 17:16:37 +0200231 _PyObject_ASSERT(self,
Victor Stinner45ec5b92020-04-08 01:42:27 +0200232 (!_PyType_IS_GC(Py_TYPE(self))
Victor Stinner24702042018-10-26 17:16:37 +0200233 || _PyObject_GC_IS_TRACKED(self)));
Victor Stinner49932fe2020-02-03 17:55:05 +0100234 /* If Py_REF_DEBUG macro is defined, _Py_NewReference() increased
235 _Py_RefTotal, so we need to undo that. */
236#ifdef Py_REF_DEBUG
237 _Py_RefTotal--;
238#endif
Antoine Pitrou796564c2013-07-30 19:59:21 +0200239 return -1;
240}
241
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000242int
243PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (PyErr_CheckSignals())
247 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000248#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (PyOS_CheckStack()) {
250 PyErr_SetString(PyExc_MemoryError, "stack overflow");
251 return -1;
252 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000253#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 clearerr(fp); /* Clear any previous error condition */
255 if (op == NULL) {
256 Py_BEGIN_ALLOW_THREADS
257 fprintf(fp, "<nil>");
258 Py_END_ALLOW_THREADS
259 }
260 else {
Victor Stinnera93c51e2020-02-07 00:38:59 +0100261 if (Py_REFCNT(op) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* XXX(twouters) cast refcount to long until %zd is
263 universally available */
264 Py_BEGIN_ALLOW_THREADS
265 fprintf(fp, "<refcnt %ld at %p>",
Victor Stinnera93c51e2020-02-07 00:38:59 +0100266 (long)Py_REFCNT(op), (void *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200268 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 else {
270 PyObject *s;
271 if (flags & Py_PRINT_RAW)
272 s = PyObject_Str(op);
273 else
274 s = PyObject_Repr(op);
275 if (s == NULL)
276 ret = -1;
277 else if (PyBytes_Check(s)) {
278 fwrite(PyBytes_AS_STRING(s), 1,
279 PyBytes_GET_SIZE(s), fp);
280 }
281 else if (PyUnicode_Check(s)) {
282 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200283 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600284 if (t == NULL) {
285 ret = -1;
286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 else {
288 fwrite(PyBytes_AS_STRING(t), 1,
289 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000290 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 }
292 }
293 else {
294 PyErr_Format(PyExc_TypeError,
295 "str() or repr() returned '%.100s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100296 Py_TYPE(s)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 ret = -1;
298 }
299 Py_XDECREF(s);
300 }
301 }
302 if (ret == 0) {
303 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300304 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 clearerr(fp);
306 ret = -1;
307 }
308 }
309 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000310}
311
Guido van Rossum38938152006-08-21 23:36:26 +0000312/* For debugging convenience. Set a breakpoint here and call it from your DLL */
313void
Thomas Woutersb2137042007-02-01 18:02:27 +0000314_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000315{
316}
317
Neal Norwitz1a997502003-01-13 20:13:12 +0000318
Victor Stinner4c409be2019-04-11 13:01:15 +0200319/* Heuristic checking if the object memory is uninitialized or deallocated.
320 Rely on the debug hooks on Python memory allocators:
321 see _PyMem_IsPtrFreed().
Victor Stinner82af0b62018-10-23 17:39:40 +0200322
323 The function can be used to prevent segmentation fault on dereferencing
Victor Stinner4c409be2019-04-11 13:01:15 +0200324 pointers like 0xDDDDDDDDDDDDDDDD. */
Victor Stinner82af0b62018-10-23 17:39:40 +0200325int
326_PyObject_IsFreed(PyObject *op)
327{
Victor Stinner58ac7002020-02-07 03:04:21 +0100328 if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(Py_TYPE(op))) {
Victor Stinner2cf5d322018-11-22 16:32:57 +0100329 return 1;
330 }
Victor Stinner2b00db62019-04-11 11:33:27 +0200331 /* ignore op->ob_ref: its value can have be modified
Victor Stinner82af0b62018-10-23 17:39:40 +0200332 by Py_INCREF() and Py_DECREF(). */
333#ifdef Py_TRACE_REFS
Pablo Galindo36e33c32019-10-08 00:43:14 +0100334 if (op->_ob_next != NULL && _PyMem_IsPtrFreed(op->_ob_next)) {
Victor Stinner2b00db62019-04-11 11:33:27 +0200335 return 1;
336 }
Pablo Galindo36e33c32019-10-08 00:43:14 +0100337 if (op->_ob_prev != NULL && _PyMem_IsPtrFreed(op->_ob_prev)) {
338 return 1;
339 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200340#endif
Victor Stinner2b00db62019-04-11 11:33:27 +0200341 return 0;
Victor Stinner82af0b62018-10-23 17:39:40 +0200342}
343
344
Barry Warsaw9bf16442001-01-23 16:24:35 +0000345/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000346void
347_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000348{
Victor Stinner82af0b62018-10-23 17:39:40 +0200349 if (_PyObject_IsFreed(op)) {
350 /* It seems like the object memory has been freed:
351 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +0200352 fprintf(stderr, "<object at %p is freed>\n", op);
Victor Stinner68762572019-10-07 18:42:01 +0200353 fflush(stderr);
Victor Stinner2cf5d322018-11-22 16:32:57 +0100354 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200355 }
356
Victor Stinner68762572019-10-07 18:42:01 +0200357 /* first, write fields which are the least likely to crash */
358 fprintf(stderr, "object address : %p\n", (void *)op);
Victor Stinner82af0b62018-10-23 17:39:40 +0200359 /* XXX(twouters) cast refcount to long until %zd is
360 universally available */
Victor Stinnera93c51e2020-02-07 00:38:59 +0100361 fprintf(stderr, "object refcount : %ld\n", (long)Py_REFCNT(op));
Victor Stinner68762572019-10-07 18:42:01 +0200362 fflush(stderr);
363
364 PyTypeObject *type = Py_TYPE(op);
365 fprintf(stderr, "object type : %p\n", type);
366 fprintf(stderr, "object type name: %s\n",
367 type==NULL ? "NULL" : type->tp_name);
368
369 /* the most dangerous part */
370 fprintf(stderr, "object repr : ");
371 fflush(stderr);
372
373 PyGILState_STATE gil = PyGILState_Ensure();
374 PyObject *error_type, *error_value, *error_traceback;
375 PyErr_Fetch(&error_type, &error_value, &error_traceback);
376
377 (void)PyObject_Print(op, stderr, 0);
378 fflush(stderr);
379
380 PyErr_Restore(error_type, error_value, error_traceback);
381 PyGILState_Release(gil);
382
383 fprintf(stderr, "\n");
Victor Stinner82af0b62018-10-23 17:39:40 +0200384 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000385}
Barry Warsaw903138f2001-01-23 16:33:18 +0000386
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000387PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000388PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyObject *res;
391 if (PyErr_CheckSignals())
392 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000393#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (PyOS_CheckStack()) {
395 PyErr_SetString(PyExc_MemoryError, "stack overflow");
396 return NULL;
397 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000398#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (v == NULL)
400 return PyUnicode_FromString("<NULL>");
401 if (Py_TYPE(v)->tp_repr == NULL)
402 return PyUnicode_FromFormat("<%s object at %p>",
Victor Stinner58ac7002020-02-07 03:04:21 +0100403 Py_TYPE(v)->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200404
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100405 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner33824f62013-08-26 14:05:19 +0200406#ifdef Py_DEBUG
407 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100408 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000409 caller loses its exception */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100410 assert(!_PyErr_Occurred(tstate));
Victor Stinner33824f62013-08-26 14:05:19 +0200411#endif
412
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200413 /* It is possible for a type to have a tp_repr representation that loops
414 infinitely. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100415 if (_Py_EnterRecursiveCall(tstate,
416 " while getting the repr of an object")) {
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200417 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100418 }
Victor Stinner58ac7002020-02-07 03:04:21 +0100419 res = (*Py_TYPE(v)->tp_repr)(v);
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100420 _Py_LeaveRecursiveCall(tstate);
421
422 if (res == NULL) {
Victor Stinner0a54cf12011-12-01 03:22:44 +0100423 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100424 }
Victor Stinner0a54cf12011-12-01 03:22:44 +0100425 if (!PyUnicode_Check(res)) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100426 _PyErr_Format(tstate, PyExc_TypeError,
427 "__repr__ returned non-string (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100428 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 Py_DECREF(res);
430 return NULL;
431 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100432#ifndef Py_DEBUG
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100433 if (PyUnicode_READY(res) < 0) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100434 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100435 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100436#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438}
439
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000441PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 PyObject *res;
444 if (PyErr_CheckSignals())
445 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000446#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (PyOS_CheckStack()) {
448 PyErr_SetString(PyExc_MemoryError, "stack overflow");
449 return NULL;
450 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000451#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (v == NULL)
453 return PyUnicode_FromString("<NULL>");
454 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100455#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100456 if (PyUnicode_READY(v) < 0)
457 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100458#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 Py_INCREF(v);
460 return v;
461 }
462 if (Py_TYPE(v)->tp_str == NULL)
463 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000464
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100465 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner33824f62013-08-26 14:05:19 +0200466#ifdef Py_DEBUG
467 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100468 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000469 caller loses its exception */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100470 assert(!_PyErr_Occurred(tstate));
Victor Stinner33824f62013-08-26 14:05:19 +0200471#endif
472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 /* It is possible for a type to have a tp_str representation that loops
474 infinitely. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100475 if (_Py_EnterRecursiveCall(tstate, " while getting the str of an object")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 res = (*Py_TYPE(v)->tp_str)(v);
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100479 _Py_LeaveRecursiveCall(tstate);
480
481 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100483 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (!PyUnicode_Check(res)) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100485 _PyErr_Format(tstate, PyExc_TypeError,
486 "__str__ returned non-string (type %.200s)",
487 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 Py_DECREF(res);
489 return NULL;
490 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100491#ifndef Py_DEBUG
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100492 if (PyUnicode_READY(res) < 0) {
Victor Stinner4ead7c72011-11-20 19:48:36 +0100493 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100494 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100495#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100496 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000498}
499
Georg Brandl559e5d72008-06-11 18:37:52 +0000500PyObject *
501PyObject_ASCII(PyObject *v)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 repr = PyObject_Repr(v);
506 if (repr == NULL)
507 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000508
Victor Stinneraf037572013-04-14 18:44:10 +0200509 if (PyUnicode_IS_ASCII(repr))
510 return repr;
511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200513 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 Py_DECREF(repr);
515 if (ascii == NULL)
516 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 res = PyUnicode_DecodeASCII(
519 PyBytes_AS_STRING(ascii),
520 PyBytes_GET_SIZE(ascii),
521 NULL);
522
523 Py_DECREF(ascii);
524 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000525}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000526
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000527PyObject *
528PyObject_Bytes(PyObject *v)
529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (v == NULL)
533 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (PyBytes_CheckExact(v)) {
536 Py_INCREF(v);
537 return v;
538 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000539
Benjamin Petersonce798522012-01-22 11:24:29 -0500540 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100542 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 Py_DECREF(func);
544 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000545 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000547 PyErr_Format(PyExc_TypeError,
548 "__bytes__ returned non-bytes (type %.200s)",
549 Py_TYPE(result)->tp_name);
550 Py_DECREF(result);
551 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 }
553 return result;
554 }
555 else if (PyErr_Occurred())
556 return NULL;
557 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000558}
559
Jeroen Demeyerbf17d412019-11-05 16:48:04 +0100560
561/*
562def _PyObject_FunctionStr(x):
563 try:
564 qualname = x.__qualname__
565 except AttributeError:
566 return str(x)
567 try:
568 mod = x.__module__
569 if mod is not None and mod != 'builtins':
570 return f"{x.__module__}.{qualname}()"
571 except AttributeError:
572 pass
573 return qualname
574*/
575PyObject *
576_PyObject_FunctionStr(PyObject *x)
577{
578 _Py_IDENTIFIER(__module__);
579 _Py_IDENTIFIER(__qualname__);
580 _Py_IDENTIFIER(builtins);
581 assert(!PyErr_Occurred());
582 PyObject *qualname;
583 int ret = _PyObject_LookupAttrId(x, &PyId___qualname__, &qualname);
584 if (qualname == NULL) {
585 if (ret < 0) {
586 return NULL;
587 }
588 return PyObject_Str(x);
589 }
590 PyObject *module;
591 PyObject *result = NULL;
592 ret = _PyObject_LookupAttrId(x, &PyId___module__, &module);
593 if (module != NULL && module != Py_None) {
594 PyObject *builtinsname = _PyUnicode_FromId(&PyId_builtins);
595 if (builtinsname == NULL) {
596 goto done;
597 }
598 ret = PyObject_RichCompareBool(module, builtinsname, Py_NE);
599 if (ret < 0) {
600 // error
601 goto done;
602 }
603 if (ret > 0) {
604 result = PyUnicode_FromFormat("%S.%S()", module, qualname);
605 goto done;
606 }
607 }
608 else if (ret < 0) {
609 goto done;
610 }
611 result = PyUnicode_FromFormat("%S()", qualname);
612done:
613 Py_DECREF(qualname);
614 Py_XDECREF(module);
615 return result;
616}
617
Mark Dickinsonc008a172009-02-01 13:59:22 +0000618/* For Python 3.0.1 and later, the old three-way comparison has been
619 completely removed in favour of rich comparisons. PyObject_Compare() and
620 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200621 The old tp_compare slot has been renamed to tp_as_async, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000622 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000623
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000624 See (*) below for practical amendments.
625
Mark Dickinsonc008a172009-02-01 13:59:22 +0000626 tp_richcompare gets called with a first argument of the appropriate type
627 and a second object of an arbitrary type. We never do any kind of
628 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000629
Mark Dickinsonc008a172009-02-01 13:59:22 +0000630 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000631
632 NULL if an exception occurred
633 NotImplemented if the requested comparison is not implemented
634 any other false value if the requested comparison is false
635 any other true value if the requested comparison is true
636
637 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
638 NotImplemented.
639
640 (*) Practical amendments:
641
642 - If rich comparison returns NotImplemented, == and != are decided by
643 comparing the object pointer (i.e. falling back to the base object
644 implementation).
645
Guido van Rossuma4073002002-05-31 20:03:54 +0000646*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000647
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000648/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000649int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000650
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200651static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000652
653/* Perform a rich comparison, raising TypeError when the requested comparison
654 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000655static PyObject *
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100656do_richcompare(PyThreadState *tstate, PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 richcmpfunc f;
659 PyObject *res;
660 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000661
Andy Lester55728702020-03-06 16:53:17 -0600662 if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
Victor Stinner58ac7002020-02-07 03:04:21 +0100663 PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
664 (f = Py_TYPE(w)->tp_richcompare) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 checked_reverse_op = 1;
666 res = (*f)(w, v, _Py_SwappedOp[op]);
667 if (res != Py_NotImplemented)
668 return res;
669 Py_DECREF(res);
670 }
Victor Stinner58ac7002020-02-07 03:04:21 +0100671 if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 res = (*f)(v, w, op);
673 if (res != Py_NotImplemented)
674 return res;
675 Py_DECREF(res);
676 }
Victor Stinner58ac7002020-02-07 03:04:21 +0100677 if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 res = (*f)(w, v, _Py_SwappedOp[op]);
679 if (res != Py_NotImplemented)
680 return res;
681 Py_DECREF(res);
682 }
683 /* If neither object implements it, provide a sensible default
684 for == and !=, but raise an exception for ordering. */
685 switch (op) {
686 case Py_EQ:
687 res = (v == w) ? Py_True : Py_False;
688 break;
689 case Py_NE:
690 res = (v != w) ? Py_True : Py_False;
691 break;
692 default:
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100693 _PyErr_Format(tstate, PyExc_TypeError,
694 "'%s' not supported between instances of '%.100s' and '%.100s'",
695 opstrings[op],
Victor Stinner58ac7002020-02-07 03:04:21 +0100696 Py_TYPE(v)->tp_name,
697 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 return NULL;
699 }
700 Py_INCREF(res);
701 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000702}
703
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000704/* Perform a rich comparison with object result. This wraps do_richcompare()
705 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000706
Guido van Rossume797ec12001-01-17 15:24:28 +0000707PyObject *
708PyObject_RichCompare(PyObject *v, PyObject *w, int op)
709{
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100710 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossume797ec12001-01-17 15:24:28 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 assert(Py_LT <= op && op <= Py_GE);
713 if (v == NULL || w == NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100714 if (!_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyErr_BadInternalCall();
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100716 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return NULL;
718 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100719 if (_Py_EnterRecursiveCall(tstate, " in comparison")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100721 }
722 PyObject *res = do_richcompare(tstate, v, w, op);
723 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000725}
726
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000727/* Perform a rich comparison with integer result. This wraps
728 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000729int
730PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *res;
733 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 /* Quick result when objects are the same.
736 Guarantees that identity implies equality. */
737 if (v == w) {
738 if (op == Py_EQ)
739 return 1;
740 else if (op == Py_NE)
741 return 0;
742 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 res = PyObject_RichCompare(v, w, op);
745 if (res == NULL)
746 return -1;
747 if (PyBool_Check(res))
748 ok = (res == Py_True);
749 else
750 ok = PyObject_IsTrue(res);
751 Py_DECREF(res);
752 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000753}
Fred Drake13634cf2000-06-29 19:17:04 +0000754
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100755Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000756PyObject_HashNotImplemented(PyObject *v)
757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
759 Py_TYPE(v)->tp_name);
760 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000761}
Fred Drake13634cf2000-06-29 19:17:04 +0000762
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000763Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000764PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyTypeObject *tp = Py_TYPE(v);
767 if (tp->tp_hash != NULL)
768 return (*tp->tp_hash)(v);
769 /* To keep to the general practice that inheriting
770 * solely from object in C code should work without
771 * an explicit call to PyType_Ready, we implicitly call
772 * PyType_Ready here and then check the tp_hash slot again
773 */
774 if (tp->tp_dict == NULL) {
775 if (PyType_Ready(tp) < 0)
776 return -1;
777 if (tp->tp_hash != NULL)
778 return (*tp->tp_hash)(v);
779 }
780 /* Otherwise, the object can't be hashed */
781 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000782}
783
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000784PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000785PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (Py_TYPE(v)->tp_getattr != NULL)
790 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900791 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (w == NULL)
793 return NULL;
794 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100795 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000797}
798
799int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000800PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PyObject *res = PyObject_GetAttrString(v, name);
803 if (res != NULL) {
804 Py_DECREF(res);
805 return 1;
806 }
807 PyErr_Clear();
808 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000809}
810
811int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000812PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyObject *s;
815 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (Py_TYPE(v)->tp_setattr != NULL)
818 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
819 s = PyUnicode_InternFromString(name);
820 if (s == NULL)
821 return -1;
822 res = PyObject_SetAttr(v, s, w);
823 Py_XDECREF(s);
824 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000825}
826
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500827int
828_PyObject_IsAbstract(PyObject *obj)
829{
830 int res;
831 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500832
833 if (obj == NULL)
834 return 0;
835
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200836 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
837 if (res > 0) {
838 res = PyObject_IsTrue(isabstract);
839 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500840 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500841 return res;
842}
843
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000844PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200845_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
846{
847 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100848 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200849 if (!oname)
850 return NULL;
851 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200852 return result;
853}
854
855int
856_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
857{
858 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100859 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200860 if (!oname)
861 return -1;
862 result = PyObject_HasAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200863 return result;
864}
865
866int
867_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
868{
869 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100870 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200871 if (!oname)
872 return -1;
873 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200874 return result;
875}
876
877PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000878PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (!PyUnicode_Check(name)) {
883 PyErr_Format(PyExc_TypeError,
884 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100885 Py_TYPE(name)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 return NULL;
887 }
888 if (tp->tp_getattro != NULL)
889 return (*tp->tp_getattro)(v, name);
890 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200891 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (name_str == NULL)
893 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200894 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 }
896 PyErr_Format(PyExc_AttributeError,
897 "'%.50s' object has no attribute '%U'",
898 tp->tp_name, name);
899 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000900}
901
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200902int
903_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900904{
905 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900906
907 if (!PyUnicode_Check(name)) {
908 PyErr_Format(PyExc_TypeError,
909 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100910 Py_TYPE(name)->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200911 *result = NULL;
912 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900913 }
914
915 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200916 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
917 if (*result != NULL) {
918 return 1;
919 }
920 if (PyErr_Occurred()) {
921 return -1;
922 }
923 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900924 }
925 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200926 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900927 }
928 else if (tp->tp_getattr != NULL) {
929 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200930 if (name_str == NULL) {
931 *result = NULL;
932 return -1;
933 }
934 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900935 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900936 else {
937 *result = NULL;
938 return 0;
939 }
940
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200941 if (*result != NULL) {
942 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900943 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200944 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
945 return -1;
946 }
947 PyErr_Clear();
948 return 0;
949}
950
951int
952_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
953{
954 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
955 if (!oname) {
956 *result = NULL;
957 return -1;
958 }
959 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +0900960}
961
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000962int
Fred Drake100814d2000-07-09 15:48:49 +0000963PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000964{
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200965 PyObject *res;
966 if (_PyObject_LookupAttr(v, name, &res) < 0) {
967 PyErr_Clear();
968 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200970 if (res == NULL) {
971 return 0;
972 }
973 Py_DECREF(res);
974 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000975}
976
977int
Fred Drake100814d2000-07-09 15:48:49 +0000978PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyTypeObject *tp = Py_TYPE(v);
981 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (!PyUnicode_Check(name)) {
984 PyErr_Format(PyExc_TypeError,
985 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100986 Py_TYPE(name)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return -1;
988 }
989 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyUnicode_InternInPlace(&name);
992 if (tp->tp_setattro != NULL) {
993 err = (*tp->tp_setattro)(v, name, value);
994 Py_DECREF(name);
995 return err;
996 }
997 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200998 const char *name_str = PyUnicode_AsUTF8(name);
Zackery Spytze0dcb852019-04-28 06:58:52 -0600999 if (name_str == NULL) {
1000 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 return -1;
Zackery Spytze0dcb852019-04-28 06:58:52 -06001002 }
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001003 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 Py_DECREF(name);
1005 return err;
1006 }
1007 Py_DECREF(name);
Victor Stinnera93c51e2020-02-07 00:38:59 +01001008 _PyObject_ASSERT(name, Py_REFCNT(name) >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1010 PyErr_Format(PyExc_TypeError,
1011 "'%.100s' object has no attributes "
1012 "(%s .%U)",
1013 tp->tp_name,
1014 value==NULL ? "del" : "assign to",
1015 name);
1016 else
1017 PyErr_Format(PyExc_TypeError,
1018 "'%.100s' object has only read-only attributes "
1019 "(%s .%U)",
1020 tp->tp_name,
1021 value==NULL ? "del" : "assign to",
1022 name);
1023 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024}
1025
1026/* Helper to get a pointer to an object's __dict__ slot, if any */
1027
1028PyObject **
1029_PyObject_GetDictPtr(PyObject *obj)
1030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 Py_ssize_t dictoffset;
1032 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 dictoffset = tp->tp_dictoffset;
1035 if (dictoffset == 0)
1036 return NULL;
1037 if (dictoffset < 0) {
Victor Stinnerc65b3202020-02-07 11:18:33 +01001038 Py_ssize_t tsize = Py_SIZE(obj);
1039 if (tsize < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 tsize = -tsize;
Victor Stinnerc65b3202020-02-07 11:18:33 +01001041 }
1042 size_t size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001045 _PyObject_ASSERT(obj, dictoffset > 0);
1046 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 }
1048 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001049}
1050
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001052PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 Py_INCREF(obj);
1055 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001056}
1057
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001058/* Helper used when the __next__ method is removed from a type:
1059 tp_iternext is never NULL and can be safely called without checking
1060 on every iteration.
1061 */
1062
1063PyObject *
1064_PyObject_NextNotImplemented(PyObject *self)
1065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyErr_Format(PyExc_TypeError,
1067 "'%.200s' object is not iterable",
1068 Py_TYPE(self)->tp_name);
1069 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001070}
1071
Yury Selivanovf2392132016-12-13 19:03:51 -05001072
1073/* Specialized version of _PyObject_GenericGetAttrWithDict
1074 specifically for the LOAD_METHOD opcode.
1075
1076 Return 1 if a method is found, 0 if it's a regular attribute
1077 from __dict__ or something returned by using a descriptor
1078 protocol.
1079
1080 `method` will point to the resolved attribute or NULL. In the
1081 latter case, an error will be set.
1082*/
1083int
1084_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1085{
1086 PyTypeObject *tp = Py_TYPE(obj);
1087 PyObject *descr;
1088 descrgetfunc f = NULL;
1089 PyObject **dictptr, *dict;
1090 PyObject *attr;
1091 int meth_found = 0;
1092
1093 assert(*method == NULL);
1094
1095 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1096 || !PyUnicode_Check(name)) {
1097 *method = PyObject_GetAttr(obj, name);
1098 return 0;
1099 }
1100
1101 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1102 return 0;
1103
1104 descr = _PyType_Lookup(tp, name);
1105 if (descr != NULL) {
1106 Py_INCREF(descr);
Victor Stinner45ec5b92020-04-08 01:42:27 +02001107 if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001108 meth_found = 1;
1109 } else {
Victor Stinner58ac7002020-02-07 03:04:21 +01001110 f = Py_TYPE(descr)->tp_descr_get;
Yury Selivanovf2392132016-12-13 19:03:51 -05001111 if (f != NULL && PyDescr_IsData(descr)) {
Victor Stinner58ac7002020-02-07 03:04:21 +01001112 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
Yury Selivanovf2392132016-12-13 19:03:51 -05001113 Py_DECREF(descr);
1114 return 0;
1115 }
1116 }
1117 }
1118
1119 dictptr = _PyObject_GetDictPtr(obj);
1120 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1121 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001122 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001123 if (attr != NULL) {
1124 Py_INCREF(attr);
1125 *method = attr;
1126 Py_DECREF(dict);
1127 Py_XDECREF(descr);
1128 return 0;
1129 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001130 else {
1131 Py_DECREF(dict);
1132 if (PyErr_Occurred()) {
1133 Py_XDECREF(descr);
1134 return 0;
1135 }
1136 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001137 }
1138
1139 if (meth_found) {
1140 *method = descr;
1141 return 1;
1142 }
1143
1144 if (f != NULL) {
1145 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1146 Py_DECREF(descr);
1147 return 0;
1148 }
1149
1150 if (descr != NULL) {
1151 *method = descr;
1152 return 0;
1153 }
1154
1155 PyErr_Format(PyExc_AttributeError,
1156 "'%.50s' object has no attribute '%U'",
1157 tp->tp_name, name);
1158 return 0;
1159}
1160
1161/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001162
Raymond Hettinger01538262003-03-17 08:24:35 +00001163PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001164_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1165 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001166{
Yury Selivanovf2392132016-12-13 19:03:51 -05001167 /* Make sure the logic of _PyObject_GetMethod is in sync with
1168 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001169
1170 When suppress=1, this function suppress AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001171 */
1172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 PyTypeObject *tp = Py_TYPE(obj);
1174 PyObject *descr = NULL;
1175 PyObject *res = NULL;
1176 descrgetfunc f;
1177 Py_ssize_t dictoffset;
1178 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (!PyUnicode_Check(name)){
1181 PyErr_Format(PyExc_TypeError,
1182 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +01001183 Py_TYPE(name)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 return NULL;
1185 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001186 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (tp->tp_dict == NULL) {
1189 if (PyType_Ready(tp) < 0)
1190 goto done;
1191 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 f = NULL;
1196 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001197 Py_INCREF(descr);
Victor Stinner58ac7002020-02-07 03:04:21 +01001198 f = Py_TYPE(descr)->tp_descr_get;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 if (f != NULL && PyDescr_IsData(descr)) {
Victor Stinner58ac7002020-02-07 03:04:21 +01001200 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001201 if (res == NULL && suppress &&
1202 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1203 PyErr_Clear();
1204 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 goto done;
1206 }
1207 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001208
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001209 if (dict == NULL) {
1210 /* Inline _PyObject_GetDictPtr */
1211 dictoffset = tp->tp_dictoffset;
1212 if (dictoffset != 0) {
1213 if (dictoffset < 0) {
Victor Stinnerc65b3202020-02-07 11:18:33 +01001214 Py_ssize_t tsize = Py_SIZE(obj);
1215 if (tsize < 0) {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001216 tsize = -tsize;
Victor Stinnerc65b3202020-02-07 11:18:33 +01001217 }
1218 size_t size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001219 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001220
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001221 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001222 _PyObject_ASSERT(obj, dictoffset > 0);
1223 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001225 dictptr = (PyObject **) ((char *)obj + dictoffset);
1226 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 }
1228 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001229 if (dict != NULL) {
1230 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001231 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001232 if (res != NULL) {
1233 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001234 Py_DECREF(dict);
1235 goto done;
1236 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001237 else {
1238 Py_DECREF(dict);
1239 if (PyErr_Occurred()) {
1240 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1241 PyErr_Clear();
1242 }
1243 else {
1244 goto done;
1245 }
1246 }
1247 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001248 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (f != NULL) {
1251 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001252 if (res == NULL && suppress &&
1253 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1254 PyErr_Clear();
1255 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 goto done;
1257 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (descr != NULL) {
1260 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001261 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 goto done;
1263 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001264
INADA Naoki378edee2018-01-16 20:52:41 +09001265 if (!suppress) {
1266 PyErr_Format(PyExc_AttributeError,
1267 "'%.50s' object has no attribute '%U'",
1268 tp->tp_name, name);
1269 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001270 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001271 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 Py_DECREF(name);
1273 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001274}
1275
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001276PyObject *
1277PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1278{
INADA Naoki378edee2018-01-16 20:52:41 +09001279 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001280}
1281
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001283_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1284 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 PyTypeObject *tp = Py_TYPE(obj);
1287 PyObject *descr;
1288 descrsetfunc f;
1289 PyObject **dictptr;
1290 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (!PyUnicode_Check(name)){
1293 PyErr_Format(PyExc_TypeError,
1294 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +01001295 Py_TYPE(name)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 return -1;
1297 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001298
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001299 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1300 return -1;
1301
1302 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001307 Py_INCREF(descr);
Victor Stinner58ac7002020-02-07 03:04:21 +01001308 f = Py_TYPE(descr)->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001309 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 res = f(descr, obj, value);
1311 goto done;
1312 }
1313 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001314
Steve Dowerb82e17e2019-05-23 08:45:22 -07001315 /* XXX [Steve Dower] These are really noisy - worth it? */
1316 /*if (PyType_Check(obj) || PyModule_Check(obj)) {
1317 if (value && PySys_Audit("object.__setattr__", "OOO", obj, name, value) < 0)
1318 return -1;
1319 if (!value && PySys_Audit("object.__delattr__", "OO", obj, name) < 0)
1320 return -1;
1321 }*/
1322
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001323 if (dict == NULL) {
1324 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001325 if (dictptr == NULL) {
1326 if (descr == NULL) {
1327 PyErr_Format(PyExc_AttributeError,
1328 "'%.100s' object has no attribute '%U'",
1329 tp->tp_name, name);
1330 }
1331 else {
1332 PyErr_Format(PyExc_AttributeError,
1333 "'%.50s' object attribute '%U' is read-only",
1334 tp->tp_name, name);
1335 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001336 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001338 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001339 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001340 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001341 Py_INCREF(dict);
1342 if (value == NULL)
1343 res = PyDict_DelItem(dict, name);
1344 else
1345 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001346 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001348 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1349 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001350
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001351 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001352 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 Py_DECREF(name);
1354 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001355}
1356
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001357int
1358PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1359{
1360 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1361}
1362
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001363int
1364PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1365{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001366 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001367 if (dictptr == NULL) {
1368 PyErr_SetString(PyExc_AttributeError,
1369 "This object has no __dict__");
1370 return -1;
1371 }
1372 if (value == NULL) {
1373 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1374 return -1;
1375 }
1376 if (!PyDict_Check(value)) {
1377 PyErr_Format(PyExc_TypeError,
1378 "__dict__ must be set to a dictionary, "
1379 "not a '%.200s'", Py_TYPE(value)->tp_name);
1380 return -1;
1381 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001382 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001383 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001384 return 0;
1385}
1386
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001387
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001388/* Test a value used as condition, e.g., in a for or if statement.
1389 Return -1 if an error occurred */
1390
1391int
Fred Drake100814d2000-07-09 15:48:49 +00001392PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 Py_ssize_t res;
1395 if (v == Py_True)
1396 return 1;
1397 if (v == Py_False)
1398 return 0;
1399 if (v == Py_None)
1400 return 0;
Victor Stinner58ac7002020-02-07 03:04:21 +01001401 else if (Py_TYPE(v)->tp_as_number != NULL &&
1402 Py_TYPE(v)->tp_as_number->nb_bool != NULL)
1403 res = (*Py_TYPE(v)->tp_as_number->nb_bool)(v);
1404 else if (Py_TYPE(v)->tp_as_mapping != NULL &&
1405 Py_TYPE(v)->tp_as_mapping->mp_length != NULL)
1406 res = (*Py_TYPE(v)->tp_as_mapping->mp_length)(v);
1407 else if (Py_TYPE(v)->tp_as_sequence != NULL &&
1408 Py_TYPE(v)->tp_as_sequence->sq_length != NULL)
1409 res = (*Py_TYPE(v)->tp_as_sequence->sq_length)(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 else
1411 return 1;
1412 /* if it is negative, it should be either -1 or -2 */
1413 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001414}
1415
Tim Peters803526b2002-07-07 05:13:56 +00001416/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001417 Return -1 if an error occurred */
1418
1419int
Fred Drake100814d2000-07-09 15:48:49 +00001420PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 int res;
1423 res = PyObject_IsTrue(v);
1424 if (res < 0)
1425 return res;
1426 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001427}
1428
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001429/* Test whether an object can be called */
1430
1431int
Fred Drake100814d2000-07-09 15:48:49 +00001432PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (x == NULL)
1435 return 0;
Victor Stinner58ac7002020-02-07 03:04:21 +01001436 return Py_TYPE(x)->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001437}
1438
Tim Peters7eea37e2001-09-04 22:08:56 +00001439
Georg Brandle32b4222007-03-10 22:13:27 +00001440/* Helper for PyObject_Dir without arguments: returns the local scope. */
1441static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001442_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001445 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001446
Victor Stinner41bb43a2013-10-29 01:19:37 +01001447 locals = PyEval_GetLocals();
1448 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 names = PyMapping_Keys(locals);
1452 if (!names)
1453 return NULL;
1454 if (!PyList_Check(names)) {
1455 PyErr_Format(PyExc_TypeError,
1456 "dir(): expected keys() of locals to be a list, "
1457 "not '%.200s'", Py_TYPE(names)->tp_name);
1458 Py_DECREF(names);
1459 return NULL;
1460 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001461 if (PyList_Sort(names)) {
1462 Py_DECREF(names);
1463 return NULL;
1464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 /* the locals don't need to be DECREF'd */
1466 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001467}
1468
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001469/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001470static PyObject *
1471_dir_object(PyObject *obj)
1472{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001473 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001474 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001475
Victor Stinner24702042018-10-26 17:16:37 +02001476 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001478 if (!PyErr_Occurred())
1479 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1480 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001482 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001483 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001484 Py_DECREF(dirfunc);
1485 if (result == NULL)
1486 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001487 /* return sorted(result) */
1488 sorted = PySequence_List(result);
1489 Py_DECREF(result);
1490 if (sorted == NULL)
1491 return NULL;
1492 if (PyList_Sort(sorted)) {
1493 Py_DECREF(sorted);
1494 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001496 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001497}
1498
1499/* Implementation of dir() -- if obj is NULL, returns the names in the current
1500 (local) scope. Otherwise, performs introspection of the object: returns a
1501 sorted list of attribute names (supposedly) accessible from the object
1502*/
1503PyObject *
1504PyObject_Dir(PyObject *obj)
1505{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001506 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001507}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001508
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001509/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001510None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001511There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001512so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001513*/
1514
Guido van Rossum0c182a11992-03-27 17:26:13 +00001515/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001516static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001517none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001520}
1521
Barry Warsaw9bf16442001-01-23 16:24:35 +00001522/* ARGUSED */
Victor Stinner2a4903f2020-01-30 13:09:11 +01001523static void _Py_NO_RETURN
Tim Peters803526b2002-07-07 05:13:56 +00001524none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 /* This should never get called, but we also don't want to SEGV if
1527 * we accidentally decref None out of existence.
1528 */
1529 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001530}
1531
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001532static PyObject *
1533none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1534{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001535 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001536 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1537 return NULL;
1538 }
1539 Py_RETURN_NONE;
1540}
1541
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001542static int
1543none_bool(PyObject *v)
1544{
1545 return 0;
1546}
1547
1548static PyNumberMethods none_as_number = {
1549 0, /* nb_add */
1550 0, /* nb_subtract */
1551 0, /* nb_multiply */
1552 0, /* nb_remainder */
1553 0, /* nb_divmod */
1554 0, /* nb_power */
1555 0, /* nb_negative */
1556 0, /* nb_positive */
1557 0, /* nb_absolute */
1558 (inquiry)none_bool, /* nb_bool */
1559 0, /* nb_invert */
1560 0, /* nb_lshift */
1561 0, /* nb_rshift */
1562 0, /* nb_and */
1563 0, /* nb_xor */
1564 0, /* nb_or */
1565 0, /* nb_int */
1566 0, /* nb_reserved */
1567 0, /* nb_float */
1568 0, /* nb_inplace_add */
1569 0, /* nb_inplace_subtract */
1570 0, /* nb_inplace_multiply */
1571 0, /* nb_inplace_remainder */
1572 0, /* nb_inplace_power */
1573 0, /* nb_inplace_lshift */
1574 0, /* nb_inplace_rshift */
1575 0, /* nb_inplace_and */
1576 0, /* nb_inplace_xor */
1577 0, /* nb_inplace_or */
1578 0, /* nb_floor_divide */
1579 0, /* nb_true_divide */
1580 0, /* nb_inplace_floor_divide */
1581 0, /* nb_inplace_true_divide */
1582 0, /* nb_index */
1583};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001584
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001585PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1587 "NoneType",
1588 0,
1589 0,
1590 none_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001591 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 0, /*tp_getattr*/
1593 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001594 0, /*tp_as_async*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001596 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 0, /*tp_as_sequence*/
1598 0, /*tp_as_mapping*/
1599 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001600 0, /*tp_call */
1601 0, /*tp_str */
1602 0, /*tp_getattro */
1603 0, /*tp_setattro */
1604 0, /*tp_as_buffer */
1605 Py_TPFLAGS_DEFAULT, /*tp_flags */
1606 0, /*tp_doc */
1607 0, /*tp_traverse */
1608 0, /*tp_clear */
1609 0, /*tp_richcompare */
1610 0, /*tp_weaklistoffset */
1611 0, /*tp_iter */
1612 0, /*tp_iternext */
1613 0, /*tp_methods */
1614 0, /*tp_members */
1615 0, /*tp_getset */
1616 0, /*tp_base */
1617 0, /*tp_dict */
1618 0, /*tp_descr_get */
1619 0, /*tp_descr_set */
1620 0, /*tp_dictoffset */
1621 0, /*tp_init */
1622 0, /*tp_alloc */
1623 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001624};
1625
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001626PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001627 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001628 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001629};
1630
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001631/* NotImplemented is an object that can be used to signal that an
1632 operation is not implemented for the given type combination. */
1633
1634static PyObject *
1635NotImplemented_repr(PyObject *op)
1636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001638}
1639
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001640static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301641NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001642{
1643 return PyUnicode_FromString("NotImplemented");
1644}
1645
1646static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301647 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001648 {NULL, NULL}
1649};
1650
1651static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001652notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1653{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001654 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001655 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1656 return NULL;
1657 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001658 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001659}
1660
Victor Stinner2a4903f2020-01-30 13:09:11 +01001661static void _Py_NO_RETURN
Armin Ronacher226b1db2012-10-06 14:28:58 +02001662notimplemented_dealloc(PyObject* ignore)
1663{
1664 /* This should never get called, but we also don't want to SEGV if
1665 * we accidentally decref NotImplemented out of existence.
1666 */
1667 Py_FatalError("deallocating NotImplemented");
1668}
1669
MojoVampire469325c2020-03-03 18:50:17 +00001670static int
1671notimplemented_bool(PyObject *v)
1672{
1673 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1674 "NotImplemented should not be used in a boolean context",
1675 1) < 0)
1676 {
1677 return -1;
1678 }
1679 return 1;
1680}
1681
1682static PyNumberMethods notimplemented_as_number = {
1683 .nb_bool = notimplemented_bool,
1684};
1685
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001686PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1688 "NotImplementedType",
1689 0,
1690 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001691 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001692 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 0, /*tp_getattr*/
1694 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001695 0, /*tp_as_async*/
MojoVampire469325c2020-03-03 18:50:17 +00001696 NotImplemented_repr, /*tp_repr*/
1697 &notimplemented_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 0, /*tp_as_sequence*/
1699 0, /*tp_as_mapping*/
1700 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001701 0, /*tp_call */
1702 0, /*tp_str */
1703 0, /*tp_getattro */
1704 0, /*tp_setattro */
1705 0, /*tp_as_buffer */
1706 Py_TPFLAGS_DEFAULT, /*tp_flags */
1707 0, /*tp_doc */
1708 0, /*tp_traverse */
1709 0, /*tp_clear */
1710 0, /*tp_richcompare */
1711 0, /*tp_weaklistoffset */
1712 0, /*tp_iter */
1713 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001714 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001715 0, /*tp_members */
1716 0, /*tp_getset */
1717 0, /*tp_base */
1718 0, /*tp_dict */
1719 0, /*tp_descr_get */
1720 0, /*tp_descr_set */
1721 0, /*tp_dictoffset */
1722 0, /*tp_init */
1723 0, /*tp_alloc */
1724 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001725};
1726
1727PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001729 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001730};
1731
Victor Stinner331a6a52019-05-27 16:39:22 +02001732PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01001733_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001734{
Victor Stinner7a1f6c22020-01-30 09:02:14 +01001735 PyStatus status = _PyTypes_InitSlotDefs();
1736 if (_PyStatus_EXCEPTION(status)) {
1737 return status;
1738 }
1739
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001740#define INIT_TYPE(TYPE, NAME) \
1741 do { \
1742 if (PyType_Ready(TYPE) < 0) { \
Victor Stinner331a6a52019-05-27 16:39:22 +02001743 return _PyStatus_ERR("Can't initialize " NAME " type"); \
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001744 } \
1745 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001746
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001747 INIT_TYPE(&PyBaseObject_Type, "object");
1748 INIT_TYPE(&PyType_Type, "type");
1749 INIT_TYPE(&_PyWeakref_RefType, "weakref");
1750 INIT_TYPE(&_PyWeakref_CallableProxyType, "callable weakref proxy");
1751 INIT_TYPE(&_PyWeakref_ProxyType, "weakref proxy");
1752 INIT_TYPE(&PyLong_Type, "int");
1753 INIT_TYPE(&PyBool_Type, "bool");
1754 INIT_TYPE(&PyByteArray_Type, "bytearray");
1755 INIT_TYPE(&PyBytes_Type, "str");
1756 INIT_TYPE(&PyList_Type, "list");
1757 INIT_TYPE(&_PyNone_Type, "None");
1758 INIT_TYPE(&_PyNotImplemented_Type, "NotImplemented");
1759 INIT_TYPE(&PyTraceBack_Type, "traceback");
1760 INIT_TYPE(&PySuper_Type, "super");
1761 INIT_TYPE(&PyRange_Type, "range");
1762 INIT_TYPE(&PyDict_Type, "dict");
1763 INIT_TYPE(&PyDictKeys_Type, "dict keys");
1764 INIT_TYPE(&PyDictValues_Type, "dict values");
1765 INIT_TYPE(&PyDictItems_Type, "dict items");
1766 INIT_TYPE(&PyDictRevIterKey_Type, "reversed dict keys");
1767 INIT_TYPE(&PyDictRevIterValue_Type, "reversed dict values");
1768 INIT_TYPE(&PyDictRevIterItem_Type, "reversed dict items");
1769 INIT_TYPE(&PyODict_Type, "OrderedDict");
1770 INIT_TYPE(&PyODictKeys_Type, "odict_keys");
1771 INIT_TYPE(&PyODictItems_Type, "odict_items");
1772 INIT_TYPE(&PyODictValues_Type, "odict_values");
1773 INIT_TYPE(&PyODictIter_Type, "odict_keyiterator");
1774 INIT_TYPE(&PySet_Type, "set");
1775 INIT_TYPE(&PyUnicode_Type, "str");
1776 INIT_TYPE(&PySlice_Type, "slice");
1777 INIT_TYPE(&PyStaticMethod_Type, "static method");
1778 INIT_TYPE(&PyComplex_Type, "complex");
1779 INIT_TYPE(&PyFloat_Type, "float");
1780 INIT_TYPE(&PyFrozenSet_Type, "frozenset");
1781 INIT_TYPE(&PyProperty_Type, "property");
1782 INIT_TYPE(&_PyManagedBuffer_Type, "managed buffer");
1783 INIT_TYPE(&PyMemoryView_Type, "memoryview");
1784 INIT_TYPE(&PyTuple_Type, "tuple");
1785 INIT_TYPE(&PyEnum_Type, "enumerate");
1786 INIT_TYPE(&PyReversed_Type, "reversed");
1787 INIT_TYPE(&PyStdPrinter_Type, "StdPrinter");
1788 INIT_TYPE(&PyCode_Type, "code");
1789 INIT_TYPE(&PyFrame_Type, "frame");
1790 INIT_TYPE(&PyCFunction_Type, "builtin function");
1791 INIT_TYPE(&PyMethod_Type, "method");
1792 INIT_TYPE(&PyFunction_Type, "function");
1793 INIT_TYPE(&PyDictProxy_Type, "dict proxy");
1794 INIT_TYPE(&PyGen_Type, "generator");
1795 INIT_TYPE(&PyGetSetDescr_Type, "get-set descriptor");
1796 INIT_TYPE(&PyWrapperDescr_Type, "wrapper");
1797 INIT_TYPE(&_PyMethodWrapper_Type, "method wrapper");
1798 INIT_TYPE(&PyEllipsis_Type, "ellipsis");
1799 INIT_TYPE(&PyMemberDescr_Type, "member descriptor");
1800 INIT_TYPE(&_PyNamespace_Type, "namespace");
1801 INIT_TYPE(&PyCapsule_Type, "capsule");
1802 INIT_TYPE(&PyLongRangeIter_Type, "long range iterator");
1803 INIT_TYPE(&PyCell_Type, "cell");
1804 INIT_TYPE(&PyInstanceMethod_Type, "instance method");
1805 INIT_TYPE(&PyClassMethodDescr_Type, "class method descr");
1806 INIT_TYPE(&PyMethodDescr_Type, "method descr");
1807 INIT_TYPE(&PyCallIter_Type, "call iter");
1808 INIT_TYPE(&PySeqIter_Type, "sequence iterator");
Antoine Pitrou91f43802019-05-26 17:10:09 +02001809 INIT_TYPE(&PyPickleBuffer_Type, "pickle.PickleBuffer");
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001810 INIT_TYPE(&PyCoro_Type, "coroutine");
1811 INIT_TYPE(&_PyCoroWrapper_Type, "coroutine wrapper");
Eric Snowc11183c2019-03-15 16:35:46 -06001812 INIT_TYPE(&_PyInterpreterID_Type, "interpreter ID");
Victor Stinner331a6a52019-05-27 16:39:22 +02001813 return _PyStatus_OK();
Guido van Rossumba21a492001-08-16 08:17:26 +00001814
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001815#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001816}
1817
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001818
Victor Stinner40e547d2020-02-05 01:11:10 +01001819void
1820_Py_NewReference(PyObject *op)
1821{
1822 if (_Py_tracemalloc_config.tracing) {
1823 _PyTraceMalloc_NewReference(op);
1824 }
1825#ifdef Py_REF_DEBUG
1826 _Py_RefTotal++;
1827#endif
Victor Stinnerc86a1122020-02-07 01:24:29 +01001828 Py_SET_REFCNT(op, 1);
Victor Stinner40e547d2020-02-05 01:11:10 +01001829#ifdef Py_TRACE_REFS
1830 _Py_AddToAllObjects(op, 1);
1831#endif
1832}
1833
1834
Guido van Rossum84a90321996-05-22 16:34:47 +00001835#ifdef Py_TRACE_REFS
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001836void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001837_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001838{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001839 if (Py_REFCNT(op) < 0) {
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001840 _PyObject_ASSERT_FAILED_MSG(op, "negative refcnt");
1841 }
1842
1843 if (op == &refchain ||
1844 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
1845 {
1846 _PyObject_ASSERT_FAILED_MSG(op, "invalid object chain");
1847 }
1848
Guido van Rossumbffd6832000-01-20 22:32:56 +00001849#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001850 PyObject *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001852 if (p == op) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 break;
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 }
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001856 if (p == &refchain) {
1857 /* Not found */
1858 _PyObject_ASSERT_FAILED_MSG(op,
1859 "object not found in the objects list");
1860 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001861#endif
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 op->_ob_next->_ob_prev = op->_ob_prev;
1864 op->_ob_prev->_ob_next = op->_ob_next;
1865 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001866}
1867
Tim Peters269b2a62003-04-17 19:52:29 +00001868/* Print all live objects. Because PyObject_Print is called, the
1869 * interpreter must be in a healthy state.
1870 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001871void
Fred Drake100814d2000-07-09 15:48:49 +00001872_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 PyObject *op;
1875 fprintf(fp, "Remaining objects:\n");
1876 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Victor Stinnera93c51e2020-02-07 00:38:59 +01001877 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", (void *)op, Py_REFCNT(op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (PyObject_Print(op, fp, 0) != 0)
1879 PyErr_Clear();
1880 putc('\n', fp);
1881 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001882}
1883
Tim Peters269b2a62003-04-17 19:52:29 +00001884/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1885 * doesn't make any calls to the Python C API, so is always safe to call.
1886 */
1887void
1888_Py_PrintReferenceAddresses(FILE *fp)
1889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 PyObject *op;
1891 fprintf(fp, "Remaining object addresses:\n");
1892 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001893 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", (void *)op,
Victor Stinnera93c51e2020-02-07 00:38:59 +01001894 Py_REFCNT(op), Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001895}
1896
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001897PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001898_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 int i, n;
1901 PyObject *t = NULL;
1902 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1905 return NULL;
1906 op = refchain._ob_next;
1907 res = PyList_New(0);
1908 if (res == NULL)
1909 return NULL;
1910 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1911 while (op == self || op == args || op == res || op == t ||
Andy Lester55728702020-03-06 16:53:17 -06001912 (t != NULL && !Py_IS_TYPE(op, (PyTypeObject *) t))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 op = op->_ob_next;
1914 if (op == &refchain)
1915 return res;
1916 }
1917 if (PyList_Append(res, op) < 0) {
1918 Py_DECREF(res);
1919 return NULL;
1920 }
1921 op = op->_ob_next;
1922 }
1923 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001924}
1925
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001926#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001927
Benjamin Petersonb173f782009-05-05 22:31:58 +00001928
Guido van Rossum84a90321996-05-22 16:34:47 +00001929/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001930Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001931
1932
David Malcolm49526f42012-06-22 14:55:41 -04001933void
1934_PyObject_DebugTypeStats(FILE *out)
1935{
David Malcolm49526f42012-06-22 14:55:41 -04001936 _PyDict_DebugMallocStats(out);
1937 _PyFloat_DebugMallocStats(out);
1938 _PyFrame_DebugMallocStats(out);
1939 _PyList_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001940 _PyTuple_DebugMallocStats(out);
1941}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001942
Guido van Rossum86610361998-04-10 22:32:46 +00001943/* These methods are used to control infinite recursion in repr, str, print,
1944 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00001945 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00001946 Py_ReprLeave() to avoid infinite recursion.
1947
1948 Py_ReprEnter() returns 0 the first time it is called for a particular
1949 object and 1 every time thereafter. It returns -1 if an exception
1950 occurred. Py_ReprLeave() has no return value.
1951
1952 See dictobject.c and listobject.c for examples of use.
1953*/
1954
Guido van Rossum86610361998-04-10 22:32:46 +00001955int
Fred Drake100814d2000-07-09 15:48:49 +00001956Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 PyObject *dict;
1959 PyObject *list;
1960 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02001963 /* Ignore a missing thread-state, so that this function can be called
1964 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (dict == NULL)
1966 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001967 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001969 if (PyErr_Occurred()) {
1970 return -1;
1971 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 list = PyList_New(0);
1973 if (list == NULL)
1974 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001975 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 return -1;
1977 Py_DECREF(list);
1978 }
1979 i = PyList_GET_SIZE(list);
1980 while (--i >= 0) {
1981 if (PyList_GET_ITEM(list, i) == obj)
1982 return 1;
1983 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02001984 if (PyList_Append(list, obj) < 0)
1985 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001987}
1988
1989void
Fred Drake100814d2000-07-09 15:48:49 +00001990Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyObject *dict;
1993 PyObject *list;
1994 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02001995 PyObject *error_type, *error_value, *error_traceback;
1996
1997 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 dict = PyThreadState_GetDict();
2000 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002001 goto finally;
2002
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002003 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002005 goto finally;
2006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 i = PyList_GET_SIZE(list);
2008 /* Count backwards because we always expect obj to be list[-1] */
2009 while (--i >= 0) {
2010 if (PyList_GET_ITEM(list, i) == obj) {
2011 PyList_SetSlice(list, i, i + 1, NULL);
2012 break;
2013 }
2014 }
Victor Stinner1b634932013-07-16 22:24:44 +02002015
2016finally:
2017 /* ignore exceptions because there is no way to report them. */
2018 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002019}
Guido van Rossumd724b232000-03-13 16:01:29 +00002020
Tim Peters803526b2002-07-07 05:13:56 +00002021/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002022
Tim Peters803526b2002-07-07 05:13:56 +00002023/* Add op to the _PyTrash_delete_later list. Called when the current
2024 * call-stack depth gets large. op must be a currently untracked gc'ed
2025 * object, with refcount 0. Py_DECREF must already have been called on it.
2026 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002027void
Fred Drake100814d2000-07-09 15:48:49 +00002028_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002029{
Victor Stinner72474072019-11-20 12:25:50 +01002030 PyThreadState *tstate = _PyThreadState_GET();
2031 struct _gc_runtime_state *gcstate = &tstate->interp->gc;
2032
Victor Stinner24702042018-10-26 17:16:37 +02002033 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2034 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
Victor Stinnera93c51e2020-02-07 00:38:59 +01002035 _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
Victor Stinner72474072019-11-20 12:25:50 +01002036 _PyGCHead_SET_PREV(_Py_AS_GC(op), gcstate->trash_delete_later);
2037 gcstate->trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002038}
2039
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002040/* The equivalent API, using per-thread state recursion info */
2041void
2042_PyTrash_thread_deposit_object(PyObject *op)
2043{
Victor Stinner50b48572018-11-01 01:51:40 +01002044 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner24702042018-10-26 17:16:37 +02002045 _PyObject_ASSERT(op, PyObject_IS_GC(op));
2046 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
Victor Stinnera93c51e2020-02-07 00:38:59 +01002047 _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002048 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002049 tstate->trash_delete_later = op;
2050}
2051
Min ho Kimc4cacc82019-07-31 08:16:13 +10002052/* Deallocate all the objects in the _PyTrash_delete_later list. Called when
Tim Peters803526b2002-07-07 05:13:56 +00002053 * the call-stack unwinds again.
2054 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002055void
Fred Drake100814d2000-07-09 15:48:49 +00002056_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002057{
Victor Stinner72474072019-11-20 12:25:50 +01002058 PyThreadState *tstate = _PyThreadState_GET();
2059 struct _gc_runtime_state *gcstate = &tstate->interp->gc;
2060
2061 while (gcstate->trash_delete_later) {
2062 PyObject *op = gcstate->trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002064
Victor Stinner72474072019-11-20 12:25:50 +01002065 gcstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002066 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 /* Call the deallocator directly. This used to try to
2069 * fool Py_DECREF into calling it indirectly, but
2070 * Py_DECREF was already called on this object, and in
2071 * assorted non-release builds calling Py_DECREF again ends
2072 * up distorting allocation statistics.
2073 */
Victor Stinnera93c51e2020-02-07 00:38:59 +01002074 _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
Victor Stinner72474072019-11-20 12:25:50 +01002075 ++gcstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 (*dealloc)(op);
Victor Stinner72474072019-11-20 12:25:50 +01002077 --gcstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002079}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002080
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002081/* The equivalent API, using per-thread state recursion info */
2082void
2083_PyTrash_thread_destroy_chain(void)
2084{
Victor Stinner50b48572018-11-01 01:51:40 +01002085 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002086 /* We need to increase trash_delete_nesting here, otherwise,
2087 _PyTrash_thread_destroy_chain will be called recursively
2088 and then possibly crash. An example that may crash without
2089 increase:
2090 N = 500000 # need to be large enough
2091 ob = object()
2092 tups = [(ob,) for i in range(N)]
2093 for i in range(49):
2094 tups = [(tup,) for tup in tups]
2095 del tups
2096 */
2097 assert(tstate->trash_delete_nesting == 0);
2098 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002099 while (tstate->trash_delete_later) {
2100 PyObject *op = tstate->trash_delete_later;
2101 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2102
2103 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002104 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002105
2106 /* Call the deallocator directly. This used to try to
2107 * fool Py_DECREF into calling it indirectly, but
2108 * Py_DECREF was already called on this object, and in
2109 * assorted non-release builds calling Py_DECREF again ends
2110 * up distorting allocation statistics.
2111 */
Victor Stinnera93c51e2020-02-07 00:38:59 +01002112 _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002113 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002114 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002115 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002116 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002117}
2118
Victor Stinner626bff82018-10-25 17:31:10 +02002119
Victor Stinner38965ec2020-03-13 16:51:52 +01002120int
2121_PyTrash_begin(PyThreadState *tstate, PyObject *op)
2122{
2123 if (tstate->trash_delete_nesting >= PyTrash_UNWIND_LEVEL) {
2124 /* Store the object (to be deallocated later) and jump past
2125 * Py_TRASHCAN_END, skipping the body of the deallocator */
2126 _PyTrash_thread_deposit_object(op);
2127 return 1;
2128 }
2129 ++tstate->trash_delete_nesting;
2130 return 0;
2131}
2132
2133
2134void
2135_PyTrash_end(PyThreadState *tstate)
2136{
2137 --tstate->trash_delete_nesting;
2138 if (tstate->trash_delete_later && tstate->trash_delete_nesting <= 0) {
2139 _PyTrash_thread_destroy_chain();
2140 }
2141}
2142
2143
Victor Stinner2a4903f2020-01-30 13:09:11 +01002144void _Py_NO_RETURN
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002145_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002146 const char *file, int line, const char *function)
2147{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002148 fprintf(stderr, "%s:%d: ", file, line);
2149 if (function) {
2150 fprintf(stderr, "%s: ", function);
2151 }
Victor Stinner626bff82018-10-25 17:31:10 +02002152 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002153
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002154 if (expr) {
2155 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002156 }
2157 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002158 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002159 }
2160 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002161
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002162 if (msg) {
2163 fprintf(stderr, ": %s", msg);
2164 }
2165 fprintf(stderr, "\n");
2166 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002167
Victor Stinner68762572019-10-07 18:42:01 +02002168 if (_PyObject_IsFreed(obj)) {
Victor Stinner626bff82018-10-25 17:31:10 +02002169 /* It seems like the object memory has been freed:
2170 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +02002171 fprintf(stderr, "<object at %p is freed>\n", obj);
Victor Stinner68762572019-10-07 18:42:01 +02002172 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002173 }
2174 else {
penguindustin96466302019-05-06 14:57:17 -04002175 /* Display the traceback where the object has been allocated.
Victor Stinner626bff82018-10-25 17:31:10 +02002176 Do it before dumping repr(obj), since repr() is more likely
2177 to crash than dumping the traceback. */
2178 void *ptr;
2179 PyTypeObject *type = Py_TYPE(obj);
Victor Stinner45ec5b92020-04-08 01:42:27 +02002180 if (_PyType_IS_GC(type)) {
Victor Stinner626bff82018-10-25 17:31:10 +02002181 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2182 }
2183 else {
2184 ptr = (void *)obj;
2185 }
2186 _PyMem_DumpTraceback(fileno(stderr), ptr);
2187
2188 /* This might succeed or fail, but we're about to abort, so at least
2189 try to provide any extra info we can: */
2190 _PyObject_Dump(obj);
Victor Stinner77753492019-10-07 23:44:05 +02002191
2192 fprintf(stderr, "\n");
2193 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002194 }
Victor Stinner626bff82018-10-25 17:31:10 +02002195
2196 Py_FatalError("_PyObject_AssertFailed");
2197}
2198
Victor Stinner3c09dca2018-10-30 14:48:26 +01002199
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002200void
2201_Py_Dealloc(PyObject *op)
2202{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002203 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2204#ifdef Py_TRACE_REFS
2205 _Py_ForgetReference(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002206#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002207 (*dealloc)(op);
2208}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002209
Victor Stinner38aefc52020-04-06 14:07:02 +02002210
2211PyObject **
2212PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
2213{
2214 return _PyObject_GET_WEAKREFS_LISTPTR(op);
2215}
2216
2217
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002218#ifdef __cplusplus
2219}
2220#endif