blob: 93c6315451d70fba5c917fd3ce23b6181758cdff [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 Stinnere5014be2020-04-14 17:52:15 +02005#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 Stinnere560f902020-04-14 18:30:41 +020011#include "pycore_pymem.h" // _PyMem_IsPtrFreed()
Victor Stinnere5014be2020-04-14 17:52:15 +020012#include "pycore_pystate.h" // _PyThreadState_GET()
Benjamin Petersonfd838e62009-04-20 02:09:13 +000013#include "frameobject.h"
Eric Snowc11183c2019-03-15 16:35:46 -060014#include "interpreteridobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015
Victor Stinner3359cab2021-04-02 15:45:37 +020016#ifdef Py_LIMITED_API
17 // Prevent recursive call _Py_IncRef() <=> Py_INCREF()
18# error "Py_LIMITED_API macro must not be defined"
19#endif
20
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
22extern "C" {
23#endif
24
Victor Stinner626bff82018-10-25 17:31:10 +020025/* Defined in tracemalloc.c */
26extern void _PyMem_DumpTraceback(int fd, const void *ptr);
27
Victor Stinnerbd303c12013-11-07 23:07:29 +010028_Py_IDENTIFIER(Py_Repr);
29_Py_IDENTIFIER(__bytes__);
30_Py_IDENTIFIER(__dir__);
31_Py_IDENTIFIER(__isabstractmethod__);
Victor Stinnerbd303c12013-11-07 23:07:29 +010032
Victor Stinner0fc91ee2019-04-12 21:51:34 +020033
34int
35_PyObject_CheckConsistency(PyObject *op, int check_content)
36{
Victor Stinner68762572019-10-07 18:42:01 +020037#define CHECK(expr) \
38 do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
Victor Stinner0fc91ee2019-04-12 21:51:34 +020039
Victor Stinner68762572019-10-07 18:42:01 +020040 CHECK(!_PyObject_IsFreed(op));
41 CHECK(Py_REFCNT(op) >= 1);
42
Victor Stinner58ac7002020-02-07 03:04:21 +010043 _PyType_CheckConsistency(Py_TYPE(op));
Victor Stinner0fc91ee2019-04-12 21:51:34 +020044
45 if (PyUnicode_Check(op)) {
46 _PyUnicode_CheckConsistency(op, check_content);
47 }
48 else if (PyDict_Check(op)) {
49 _PyDict_CheckConsistency(op, check_content);
50 }
51 return 1;
Victor Stinner68762572019-10-07 18:42:01 +020052
53#undef CHECK
Victor Stinner0fc91ee2019-04-12 21:51:34 +020054}
55
56
Tim Peters34592512002-07-11 06:23:50 +000057#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000058Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059
60Py_ssize_t
61_Py_GetRefTotal(void)
62{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyObject *o;
64 Py_ssize_t total = _Py_RefTotal;
Antoine Pitrou9d952542013-08-24 21:07:07 +020065 o = _PySet_Dummy;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 if (o != NULL)
Victor Stinnera93c51e2020-02-07 00:38:59 +010067 total -= Py_REFCNT(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000069}
Nick Coghland6009512014-11-20 21:39:37 +100070
71void
72_PyDebug_PrintTotalRefs(void) {
Eric Snowdae02762017-09-14 00:35:58 -070073 fprintf(stderr,
Victor Stinnerd36cf5f2020-06-10 18:38:05 +020074 "[%zd refs, %zd blocks]\n",
Eric Snowdae02762017-09-14 00:35:58 -070075 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
Nick Coghland6009512014-11-20 21:39:37 +100076}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000077#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000078
Guido van Rossum3f5da241990-12-20 15:06:42 +000079/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
80 These are used by the individual routines for object creation.
81 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000082
Tim Peters78be7992003-03-23 02:51:01 +000083#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000084/* Head of circular doubly-linked list of all objects. These are linked
85 * together via the _ob_prev and _ob_next members of a PyObject, which
86 * exist only in a Py_TRACE_REFS build.
87 */
Tim Peters78be7992003-03-23 02:51:01 +000088static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000089
Tim Peters7571a0f2003-03-23 17:52:28 +000090/* Insert op at the front of the list of all objects. If force is true,
91 * op is added even if _ob_prev and _ob_next are non-NULL already. If
92 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
93 * force should be true if and only if op points to freshly allocated,
94 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000095 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000096 * Note that objects are normally added to the list via _Py_NewReference,
97 * which is called by PyObject_Init. Not all objects are initialized that
98 * way, though; exceptions include statically allocated type objects, and
99 * statically allocated singletons (like Py_True and Py_None).
100 */
Victor Stinner58f4e1a2020-02-05 18:24:33 +0100101void
Tim Peters7571a0f2003-03-23 17:52:28 +0000102_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +0000103{
Tim Peters7571a0f2003-03-23 17:52:28 +0000104#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 if (!force) {
106 /* If it's initialized memory, op must be in or out of
107 * the list unambiguously.
108 */
Victor Stinner24702042018-10-26 17:16:37 +0200109 _PyObject_ASSERT(op, (op->_ob_prev == NULL) == (op->_ob_next == NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 }
Tim Peters78be7992003-03-23 02:51:01 +0000111#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 if (force || op->_ob_prev == NULL) {
113 op->_ob_next = refchain._ob_next;
114 op->_ob_prev = &refchain;
115 refchain._ob_next->_ob_prev = op;
116 refchain._ob_next = op;
117 }
Tim Peters7571a0f2003-03-23 17:52:28 +0000118}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +0000120
Tim Peters7c321a82002-07-09 02:57:01 +0000121#ifdef Py_REF_DEBUG
122/* Log a fatal error; doesn't return. */
123void
Victor Stinner18618e652018-10-25 17:28:11 +0200124_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
Tim Peters7c321a82002-07-09 02:57:01 +0000125{
Victor Stinnerf1d002c2018-11-21 23:53:44 +0100126 _PyObject_AssertFailed(op, NULL, "object has negative ref count",
Victor Stinner3ec9af72018-10-26 02:12:34 +0200127 filename, lineno, __func__);
Tim Peters7c321a82002-07-09 02:57:01 +0000128}
129
130#endif /* Py_REF_DEBUG */
131
Thomas Heller1328b522004-04-22 17:23:49 +0000132void
133Py_IncRef(PyObject *o)
134{
135 Py_XINCREF(o);
136}
137
138void
139Py_DecRef(PyObject *o)
140{
141 Py_XDECREF(o);
142}
143
Victor Stinner3359cab2021-04-02 15:45:37 +0200144void
145_Py_IncRef(PyObject *o)
146{
147 Py_INCREF(o);
148}
149
150void
151_Py_DecRef(PyObject *o)
152{
153 Py_DECREF(o);
154}
155
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000157PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158{
Victor Stinnerf58bd7c2020-02-05 13:12:19 +0100159 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 return PyErr_NoMemory();
Victor Stinnerf58bd7c2020-02-05 13:12:19 +0100161 }
162
Victor Stinner04fc4f22020-06-16 01:28:07 +0200163 _PyObject_Init(op, tp);
164 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165}
166
Guido van Rossumb18618d2000-05-03 23:44:39 +0000167PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000168PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000169{
Victor Stinnerf58bd7c2020-02-05 13:12:19 +0100170 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 return (PyVarObject *) PyErr_NoMemory();
Victor Stinnerf58bd7c2020-02-05 13:12:19 +0100172 }
173
Victor Stinner04fc4f22020-06-16 01:28:07 +0200174 _PyObject_InitVar(op, tp, size);
175 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000176}
177
178PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000179_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000180{
Victor Stinner32bd68c2020-12-01 10:37:39 +0100181 PyObject *op = (PyObject *) PyObject_Malloc(_PyObject_SIZE(tp));
Victor Stinner92055202020-04-08 00:38:15 +0200182 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 return PyErr_NoMemory();
Victor Stinner92055202020-04-08 00:38:15 +0200184 }
Victor Stinner04fc4f22020-06-16 01:28:07 +0200185 _PyObject_Init(op, tp);
Victor Stinner92055202020-04-08 00:38:15 +0200186 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000187}
188
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000189PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000190_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyVarObject *op;
193 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
Victor Stinner32bd68c2020-12-01 10:37:39 +0100194 op = (PyVarObject *) PyObject_Malloc(size);
Victor Stinner04fc4f22020-06-16 01:28:07 +0200195 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 return (PyVarObject *)PyErr_NoMemory();
Victor Stinner04fc4f22020-06-16 01:28:07 +0200197 }
198 _PyObject_InitVar(op, tp, nitems);
199 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000200}
201
Antoine Pitrou796564c2013-07-30 19:59:21 +0200202void
203PyObject_CallFinalizer(PyObject *self)
204{
205 PyTypeObject *tp = Py_TYPE(self);
206
Antoine Pitrouada319b2019-05-29 22:12:38 +0200207 if (tp->tp_finalize == NULL)
Antoine Pitrou796564c2013-07-30 19:59:21 +0200208 return;
209 /* tp_finalize should only be called once. */
Victor Stinner45ec5b92020-04-08 01:42:27 +0200210 if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
Antoine Pitrou796564c2013-07-30 19:59:21 +0200211 return;
212
213 tp->tp_finalize(self);
Victor Stinner45ec5b92020-04-08 01:42:27 +0200214 if (_PyType_IS_GC(tp)) {
INADA Naoki5ac9e6e2018-07-10 17:19:53 +0900215 _PyGC_SET_FINALIZED(self);
216 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200217}
218
219int
220PyObject_CallFinalizerFromDealloc(PyObject *self)
221{
Victor Stinnera93c51e2020-02-07 00:38:59 +0100222 if (Py_REFCNT(self) != 0) {
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100223 _PyObject_ASSERT_FAILED_MSG(self,
224 "PyObject_CallFinalizerFromDealloc called "
225 "on object with a non-zero refcount");
226 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200227
228 /* Temporarily resurrect the object. */
Victor Stinnerc86a1122020-02-07 01:24:29 +0100229 Py_SET_REFCNT(self, 1);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200230
231 PyObject_CallFinalizer(self);
232
Victor Stinner24702042018-10-26 17:16:37 +0200233 _PyObject_ASSERT_WITH_MSG(self,
Victor Stinnera93c51e2020-02-07 00:38:59 +0100234 Py_REFCNT(self) > 0,
Victor Stinner24702042018-10-26 17:16:37 +0200235 "refcount is too small");
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100236
237 /* Undo the temporary resurrection; can't use DECREF here, it would
238 * cause a recursive call. */
Victor Stinnerc86a1122020-02-07 01:24:29 +0100239 Py_SET_REFCNT(self, Py_REFCNT(self) - 1);
240 if (Py_REFCNT(self) == 0) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200241 return 0; /* this is the normal path out */
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100242 }
Antoine Pitrou796564c2013-07-30 19:59:21 +0200243
244 /* tp_finalize resurrected it! Make it look like the original Py_DECREF
Victor Stinner5eb8bff2020-01-30 09:01:07 +0100245 * never happened. */
Victor Stinnera93c51e2020-02-07 00:38:59 +0100246 Py_ssize_t refcnt = Py_REFCNT(self);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200247 _Py_NewReference(self);
Victor Stinnerc86a1122020-02-07 01:24:29 +0100248 Py_SET_REFCNT(self, refcnt);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200249
Victor Stinner24702042018-10-26 17:16:37 +0200250 _PyObject_ASSERT(self,
Victor Stinner45ec5b92020-04-08 01:42:27 +0200251 (!_PyType_IS_GC(Py_TYPE(self))
Victor Stinner24702042018-10-26 17:16:37 +0200252 || _PyObject_GC_IS_TRACKED(self)));
Victor Stinner49932fe2020-02-03 17:55:05 +0100253 /* If Py_REF_DEBUG macro is defined, _Py_NewReference() increased
254 _Py_RefTotal, so we need to undo that. */
255#ifdef Py_REF_DEBUG
256 _Py_RefTotal--;
257#endif
Antoine Pitrou796564c2013-07-30 19:59:21 +0200258 return -1;
259}
260
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000261int
262PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if (PyErr_CheckSignals())
266 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000267#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 if (PyOS_CheckStack()) {
269 PyErr_SetString(PyExc_MemoryError, "stack overflow");
270 return -1;
271 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000272#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 clearerr(fp); /* Clear any previous error condition */
274 if (op == NULL) {
275 Py_BEGIN_ALLOW_THREADS
276 fprintf(fp, "<nil>");
277 Py_END_ALLOW_THREADS
278 }
279 else {
Victor Stinnera93c51e2020-02-07 00:38:59 +0100280 if (Py_REFCNT(op) <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 /* XXX(twouters) cast refcount to long until %zd is
282 universally available */
283 Py_BEGIN_ALLOW_THREADS
284 fprintf(fp, "<refcnt %ld at %p>",
Victor Stinnera93c51e2020-02-07 00:38:59 +0100285 (long)Py_REFCNT(op), (void *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 Py_END_ALLOW_THREADS
Victor Stinner3ec9af72018-10-26 02:12:34 +0200287 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 else {
289 PyObject *s;
290 if (flags & Py_PRINT_RAW)
291 s = PyObject_Str(op);
292 else
293 s = PyObject_Repr(op);
294 if (s == NULL)
295 ret = -1;
296 else if (PyBytes_Check(s)) {
297 fwrite(PyBytes_AS_STRING(s), 1,
298 PyBytes_GET_SIZE(s), fp);
299 }
300 else if (PyUnicode_Check(s)) {
301 PyObject *t;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200302 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
Zackery Spytzae62f012018-10-06 00:44:25 -0600303 if (t == NULL) {
304 ret = -1;
305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 else {
307 fwrite(PyBytes_AS_STRING(t), 1,
308 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000309 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 }
311 }
312 else {
313 PyErr_Format(PyExc_TypeError,
314 "str() or repr() returned '%.100s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100315 Py_TYPE(s)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 ret = -1;
317 }
318 Py_XDECREF(s);
319 }
320 }
321 if (ret == 0) {
322 if (ferror(fp)) {
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300323 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 clearerr(fp);
325 ret = -1;
326 }
327 }
328 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329}
330
Guido van Rossum38938152006-08-21 23:36:26 +0000331/* For debugging convenience. Set a breakpoint here and call it from your DLL */
332void
Thomas Woutersb2137042007-02-01 18:02:27 +0000333_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000334{
335}
336
Neal Norwitz1a997502003-01-13 20:13:12 +0000337
Victor Stinner4c409be2019-04-11 13:01:15 +0200338/* Heuristic checking if the object memory is uninitialized or deallocated.
339 Rely on the debug hooks on Python memory allocators:
340 see _PyMem_IsPtrFreed().
Victor Stinner82af0b62018-10-23 17:39:40 +0200341
342 The function can be used to prevent segmentation fault on dereferencing
Victor Stinner4c409be2019-04-11 13:01:15 +0200343 pointers like 0xDDDDDDDDDDDDDDDD. */
Victor Stinner82af0b62018-10-23 17:39:40 +0200344int
345_PyObject_IsFreed(PyObject *op)
346{
Victor Stinner58ac7002020-02-07 03:04:21 +0100347 if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(Py_TYPE(op))) {
Victor Stinner2cf5d322018-11-22 16:32:57 +0100348 return 1;
349 }
Victor Stinner2b00db62019-04-11 11:33:27 +0200350 /* ignore op->ob_ref: its value can have be modified
Victor Stinner82af0b62018-10-23 17:39:40 +0200351 by Py_INCREF() and Py_DECREF(). */
352#ifdef Py_TRACE_REFS
Pablo Galindo36e33c32019-10-08 00:43:14 +0100353 if (op->_ob_next != NULL && _PyMem_IsPtrFreed(op->_ob_next)) {
Victor Stinner2b00db62019-04-11 11:33:27 +0200354 return 1;
355 }
Pablo Galindo36e33c32019-10-08 00:43:14 +0100356 if (op->_ob_prev != NULL && _PyMem_IsPtrFreed(op->_ob_prev)) {
357 return 1;
358 }
Victor Stinner82af0b62018-10-23 17:39:40 +0200359#endif
Victor Stinner2b00db62019-04-11 11:33:27 +0200360 return 0;
Victor Stinner82af0b62018-10-23 17:39:40 +0200361}
362
363
Barry Warsaw9bf16442001-01-23 16:24:35 +0000364/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000365void
366_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000367{
Victor Stinner82af0b62018-10-23 17:39:40 +0200368 if (_PyObject_IsFreed(op)) {
369 /* It seems like the object memory has been freed:
370 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +0200371 fprintf(stderr, "<object at %p is freed>\n", op);
Victor Stinner68762572019-10-07 18:42:01 +0200372 fflush(stderr);
Victor Stinner2cf5d322018-11-22 16:32:57 +0100373 return;
Victor Stinner82af0b62018-10-23 17:39:40 +0200374 }
375
Victor Stinner68762572019-10-07 18:42:01 +0200376 /* first, write fields which are the least likely to crash */
377 fprintf(stderr, "object address : %p\n", (void *)op);
Victor Stinner82af0b62018-10-23 17:39:40 +0200378 /* XXX(twouters) cast refcount to long until %zd is
379 universally available */
Victor Stinnera93c51e2020-02-07 00:38:59 +0100380 fprintf(stderr, "object refcount : %ld\n", (long)Py_REFCNT(op));
Victor Stinner68762572019-10-07 18:42:01 +0200381 fflush(stderr);
382
383 PyTypeObject *type = Py_TYPE(op);
384 fprintf(stderr, "object type : %p\n", type);
385 fprintf(stderr, "object type name: %s\n",
386 type==NULL ? "NULL" : type->tp_name);
387
388 /* the most dangerous part */
389 fprintf(stderr, "object repr : ");
390 fflush(stderr);
391
392 PyGILState_STATE gil = PyGILState_Ensure();
393 PyObject *error_type, *error_value, *error_traceback;
394 PyErr_Fetch(&error_type, &error_value, &error_traceback);
395
396 (void)PyObject_Print(op, stderr, 0);
397 fflush(stderr);
398
399 PyErr_Restore(error_type, error_value, error_traceback);
400 PyGILState_Release(gil);
401
402 fprintf(stderr, "\n");
Victor Stinner82af0b62018-10-23 17:39:40 +0200403 fflush(stderr);
Barry Warsaw9bf16442001-01-23 16:24:35 +0000404}
Barry Warsaw903138f2001-01-23 16:33:18 +0000405
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000407PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 PyObject *res;
410 if (PyErr_CheckSignals())
411 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000412#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (PyOS_CheckStack()) {
414 PyErr_SetString(PyExc_MemoryError, "stack overflow");
415 return NULL;
416 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000417#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (v == NULL)
419 return PyUnicode_FromString("<NULL>");
420 if (Py_TYPE(v)->tp_repr == NULL)
421 return PyUnicode_FromFormat("<%s object at %p>",
Victor Stinner58ac7002020-02-07 03:04:21 +0100422 Py_TYPE(v)->tp_name, v);
Victor Stinner33824f62013-08-26 14:05:19 +0200423
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100424 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner33824f62013-08-26 14:05:19 +0200425#ifdef Py_DEBUG
426 /* PyObject_Repr() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100427 because it can clear it (directly or indirectly) and so the
Martin Panter9955a372015-10-07 10:26:23 +0000428 caller loses its exception */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100429 assert(!_PyErr_Occurred(tstate));
Victor Stinner33824f62013-08-26 14:05:19 +0200430#endif
431
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200432 /* It is possible for a type to have a tp_repr representation that loops
433 infinitely. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100434 if (_Py_EnterRecursiveCall(tstate,
435 " while getting the repr of an object")) {
Serhiy Storchaka1fb72d22017-12-03 22:12:11 +0200436 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100437 }
Victor Stinner58ac7002020-02-07 03:04:21 +0100438 res = (*Py_TYPE(v)->tp_repr)(v);
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100439 _Py_LeaveRecursiveCall(tstate);
440
441 if (res == NULL) {
Victor Stinner0a54cf12011-12-01 03:22:44 +0100442 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100443 }
Victor Stinner0a54cf12011-12-01 03:22:44 +0100444 if (!PyUnicode_Check(res)) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100445 _PyErr_Format(tstate, PyExc_TypeError,
446 "__repr__ returned non-string (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100447 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 Py_DECREF(res);
449 return NULL;
450 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100451#ifndef Py_DEBUG
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100452 if (PyUnicode_READY(res) < 0) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100453 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100454 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100455#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457}
458
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000460PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PyObject *res;
463 if (PyErr_CheckSignals())
464 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000465#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (PyOS_CheckStack()) {
467 PyErr_SetString(PyExc_MemoryError, "stack overflow");
468 return NULL;
469 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000470#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (v == NULL)
472 return PyUnicode_FromString("<NULL>");
473 if (PyUnicode_CheckExact(v)) {
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100474#ifndef Py_DEBUG
Victor Stinner4ead7c72011-11-20 19:48:36 +0100475 if (PyUnicode_READY(v) < 0)
476 return NULL;
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100477#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Py_INCREF(v);
479 return v;
480 }
481 if (Py_TYPE(v)->tp_str == NULL)
482 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000483
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100484 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner33824f62013-08-26 14:05:19 +0200485#ifdef Py_DEBUG
486 /* PyObject_Str() must not be called with an exception set,
Victor Stinnera8cb5152017-01-18 14:12:51 +0100487 because it can clear it (directly or indirectly) and so the
Nick Coghland979e432014-02-09 10:43:21 +1000488 caller loses its exception */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100489 assert(!_PyErr_Occurred(tstate));
Victor Stinner33824f62013-08-26 14:05:19 +0200490#endif
491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 /* It is possible for a type to have a tp_str representation that loops
493 infinitely. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100494 if (_Py_EnterRecursiveCall(tstate, " while getting the str of an object")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100496 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 res = (*Py_TYPE(v)->tp_str)(v);
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100498 _Py_LeaveRecursiveCall(tstate);
499
500 if (res == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100502 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 if (!PyUnicode_Check(res)) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100504 _PyErr_Format(tstate, PyExc_TypeError,
505 "__str__ returned non-string (type %.200s)",
506 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 Py_DECREF(res);
508 return NULL;
509 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100510#ifndef Py_DEBUG
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100511 if (PyUnicode_READY(res) < 0) {
Victor Stinner4ead7c72011-11-20 19:48:36 +0100512 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100513 }
Victor Stinnerdb88ae52011-12-01 02:15:00 +0100514#endif
Victor Stinner4ead7c72011-11-20 19:48:36 +0100515 assert(_PyUnicode_CheckConsistency(res, 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000517}
518
Georg Brandl559e5d72008-06-11 18:37:52 +0000519PyObject *
520PyObject_ASCII(PyObject *v)
521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 repr = PyObject_Repr(v);
525 if (repr == NULL)
526 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000527
Victor Stinneraf037572013-04-14 18:44:10 +0200528 if (PyUnicode_IS_ASCII(repr))
529 return repr;
530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200532 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 Py_DECREF(repr);
534 if (ascii == NULL)
535 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 res = PyUnicode_DecodeASCII(
538 PyBytes_AS_STRING(ascii),
539 PyBytes_GET_SIZE(ascii),
540 NULL);
541
542 Py_DECREF(ascii);
543 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000544}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000545
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000546PyObject *
547PyObject_Bytes(PyObject *v)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 PyObject *result, *func;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (v == NULL)
552 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (PyBytes_CheckExact(v)) {
555 Py_INCREF(v);
556 return v;
557 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000558
Benjamin Petersonce798522012-01-22 11:24:29 -0500559 func = _PyObject_LookupSpecial(v, &PyId___bytes__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (func != NULL) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100561 result = _PyObject_CallNoArg(func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 Py_DECREF(func);
563 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000564 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000566 PyErr_Format(PyExc_TypeError,
567 "__bytes__ returned non-bytes (type %.200s)",
568 Py_TYPE(result)->tp_name);
569 Py_DECREF(result);
570 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 }
572 return result;
573 }
574 else if (PyErr_Occurred())
575 return NULL;
576 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000577}
578
Jeroen Demeyerbf17d412019-11-05 16:48:04 +0100579
580/*
581def _PyObject_FunctionStr(x):
582 try:
583 qualname = x.__qualname__
584 except AttributeError:
585 return str(x)
586 try:
587 mod = x.__module__
588 if mod is not None and mod != 'builtins':
589 return f"{x.__module__}.{qualname}()"
590 except AttributeError:
591 pass
592 return qualname
593*/
594PyObject *
595_PyObject_FunctionStr(PyObject *x)
596{
597 _Py_IDENTIFIER(__module__);
598 _Py_IDENTIFIER(__qualname__);
599 _Py_IDENTIFIER(builtins);
600 assert(!PyErr_Occurred());
601 PyObject *qualname;
602 int ret = _PyObject_LookupAttrId(x, &PyId___qualname__, &qualname);
603 if (qualname == NULL) {
604 if (ret < 0) {
605 return NULL;
606 }
607 return PyObject_Str(x);
608 }
609 PyObject *module;
610 PyObject *result = NULL;
611 ret = _PyObject_LookupAttrId(x, &PyId___module__, &module);
612 if (module != NULL && module != Py_None) {
613 PyObject *builtinsname = _PyUnicode_FromId(&PyId_builtins);
614 if (builtinsname == NULL) {
615 goto done;
616 }
617 ret = PyObject_RichCompareBool(module, builtinsname, Py_NE);
618 if (ret < 0) {
619 // error
620 goto done;
621 }
622 if (ret > 0) {
623 result = PyUnicode_FromFormat("%S.%S()", module, qualname);
624 goto done;
625 }
626 }
627 else if (ret < 0) {
628 goto done;
629 }
630 result = PyUnicode_FromFormat("%S()", qualname);
631done:
632 Py_DECREF(qualname);
633 Py_XDECREF(module);
634 return result;
635}
636
Mark Dickinsonc008a172009-02-01 13:59:22 +0000637/* For Python 3.0.1 and later, the old three-way comparison has been
638 completely removed in favour of rich comparisons. PyObject_Compare() and
639 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200640 The old tp_compare slot has been renamed to tp_as_async, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000641 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000642
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000643 See (*) below for practical amendments.
644
Mark Dickinsonc008a172009-02-01 13:59:22 +0000645 tp_richcompare gets called with a first argument of the appropriate type
646 and a second object of an arbitrary type. We never do any kind of
647 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000648
Mark Dickinsonc008a172009-02-01 13:59:22 +0000649 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000650
651 NULL if an exception occurred
652 NotImplemented if the requested comparison is not implemented
653 any other false value if the requested comparison is false
654 any other true value if the requested comparison is true
655
656 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
657 NotImplemented.
658
659 (*) Practical amendments:
660
661 - If rich comparison returns NotImplemented, == and != are decided by
662 comparing the object pointer (i.e. falling back to the base object
663 implementation).
664
Guido van Rossuma4073002002-05-31 20:03:54 +0000665*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000666
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000667/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000668int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000669
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200670static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000671
672/* Perform a rich comparison, raising TypeError when the requested comparison
673 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000674static PyObject *
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100675do_richcompare(PyThreadState *tstate, PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 richcmpfunc f;
678 PyObject *res;
679 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000680
Andy Lester55728702020-03-06 16:53:17 -0600681 if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
Victor Stinner58ac7002020-02-07 03:04:21 +0100682 PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
683 (f = Py_TYPE(w)->tp_richcompare) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 checked_reverse_op = 1;
685 res = (*f)(w, v, _Py_SwappedOp[op]);
686 if (res != Py_NotImplemented)
687 return res;
688 Py_DECREF(res);
689 }
Victor Stinner58ac7002020-02-07 03:04:21 +0100690 if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 res = (*f)(v, w, op);
692 if (res != Py_NotImplemented)
693 return res;
694 Py_DECREF(res);
695 }
Victor Stinner58ac7002020-02-07 03:04:21 +0100696 if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 res = (*f)(w, v, _Py_SwappedOp[op]);
698 if (res != Py_NotImplemented)
699 return res;
700 Py_DECREF(res);
701 }
702 /* If neither object implements it, provide a sensible default
703 for == and !=, but raise an exception for ordering. */
704 switch (op) {
705 case Py_EQ:
706 res = (v == w) ? Py_True : Py_False;
707 break;
708 case Py_NE:
709 res = (v != w) ? Py_True : Py_False;
710 break;
711 default:
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100712 _PyErr_Format(tstate, PyExc_TypeError,
713 "'%s' not supported between instances of '%.100s' and '%.100s'",
714 opstrings[op],
Victor Stinner58ac7002020-02-07 03:04:21 +0100715 Py_TYPE(v)->tp_name,
716 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return NULL;
718 }
719 Py_INCREF(res);
720 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000721}
722
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000723/* Perform a rich comparison with object result. This wraps do_richcompare()
724 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000725
Guido van Rossume797ec12001-01-17 15:24:28 +0000726PyObject *
727PyObject_RichCompare(PyObject *v, PyObject *w, int op)
728{
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100729 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossume797ec12001-01-17 15:24:28 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 assert(Py_LT <= op && op <= Py_GE);
732 if (v == NULL || w == NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100733 if (!_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyErr_BadInternalCall();
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100735 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return NULL;
737 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100738 if (_Py_EnterRecursiveCall(tstate, " in comparison")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return NULL;
Victor Stinnerbe434dc2019-11-05 00:51:22 +0100740 }
741 PyObject *res = do_richcompare(tstate, v, w, op);
742 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000744}
745
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000746/* Perform a rich comparison with integer result. This wraps
747 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000748int
749PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyObject *res;
752 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 /* Quick result when objects are the same.
755 Guarantees that identity implies equality. */
756 if (v == w) {
757 if (op == Py_EQ)
758 return 1;
759 else if (op == Py_NE)
760 return 0;
761 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 res = PyObject_RichCompare(v, w, op);
764 if (res == NULL)
765 return -1;
766 if (PyBool_Check(res))
767 ok = (res == Py_True);
768 else
769 ok = PyObject_IsTrue(res);
770 Py_DECREF(res);
771 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000772}
Fred Drake13634cf2000-06-29 19:17:04 +0000773
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100774Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000775PyObject_HashNotImplemented(PyObject *v)
776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
778 Py_TYPE(v)->tp_name);
779 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000780}
Fred Drake13634cf2000-06-29 19:17:04 +0000781
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000782Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000783PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyTypeObject *tp = Py_TYPE(v);
786 if (tp->tp_hash != NULL)
787 return (*tp->tp_hash)(v);
788 /* To keep to the general practice that inheriting
789 * solely from object in C code should work without
790 * an explicit call to PyType_Ready, we implicitly call
791 * PyType_Ready here and then check the tp_hash slot again
792 */
793 if (tp->tp_dict == NULL) {
794 if (PyType_Ready(tp) < 0)
795 return -1;
796 if (tp->tp_hash != NULL)
797 return (*tp->tp_hash)(v);
798 }
799 /* Otherwise, the object can't be hashed */
800 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000801}
802
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000803PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000804PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (Py_TYPE(v)->tp_getattr != NULL)
809 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
INADA Naoki3e8d6cb2017-02-21 23:57:25 +0900810 w = PyUnicode_FromString(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (w == NULL)
812 return NULL;
813 res = PyObject_GetAttr(v, w);
Victor Stinner59af08f2012-03-22 02:09:08 +0100814 Py_DECREF(w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000816}
817
818int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000819PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyObject *res = PyObject_GetAttrString(v, name);
822 if (res != NULL) {
823 Py_DECREF(res);
824 return 1;
825 }
826 PyErr_Clear();
827 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000828}
829
830int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000831PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyObject *s;
834 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 if (Py_TYPE(v)->tp_setattr != NULL)
837 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
838 s = PyUnicode_InternFromString(name);
839 if (s == NULL)
840 return -1;
841 res = PyObject_SetAttr(v, s, w);
842 Py_XDECREF(s);
843 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000844}
845
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500846int
847_PyObject_IsAbstract(PyObject *obj)
848{
849 int res;
850 PyObject* isabstract;
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500851
852 if (obj == NULL)
853 return 0;
854
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200855 res = _PyObject_LookupAttrId(obj, &PyId___isabstractmethod__, &isabstract);
856 if (res > 0) {
857 res = PyObject_IsTrue(isabstract);
858 Py_DECREF(isabstract);
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500859 }
Benjamin Petersonbfebb7b2011-12-15 15:34:02 -0500860 return res;
861}
862
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000863PyObject *
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200864_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
865{
866 PyObject *result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100867 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200868 if (!oname)
869 return NULL;
870 result = PyObject_GetAttr(v, oname);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200871 return result;
872}
873
874int
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200875_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
876{
877 int result;
Martin v. Löwisd10759f2011-11-07 13:00:05 +0100878 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200879 if (!oname)
880 return -1;
881 result = PyObject_SetAttr(v, oname, w);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200882 return result;
883}
884
885PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000886PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 if (!PyUnicode_Check(name)) {
891 PyErr_Format(PyExc_TypeError,
892 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100893 Py_TYPE(name)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return NULL;
895 }
896 if (tp->tp_getattro != NULL)
897 return (*tp->tp_getattro)(v, name);
898 if (tp->tp_getattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200899 const char *name_str = PyUnicode_AsUTF8(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 if (name_str == NULL)
901 return NULL;
Serhiy Storchaka2a404b62017-01-22 23:07:07 +0200902 return (*tp->tp_getattr)(v, (char *)name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 }
904 PyErr_Format(PyExc_AttributeError,
905 "'%.50s' object has no attribute '%U'",
906 tp->tp_name, name);
907 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000908}
909
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200910int
911_PyObject_LookupAttr(PyObject *v, PyObject *name, PyObject **result)
INADA Naoki378edee2018-01-16 20:52:41 +0900912{
913 PyTypeObject *tp = Py_TYPE(v);
INADA Naoki378edee2018-01-16 20:52:41 +0900914
915 if (!PyUnicode_Check(name)) {
916 PyErr_Format(PyExc_TypeError,
917 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100918 Py_TYPE(name)->tp_name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200919 *result = NULL;
920 return -1;
INADA Naoki378edee2018-01-16 20:52:41 +0900921 }
922
923 if (tp->tp_getattro == PyObject_GenericGetAttr) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200924 *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
925 if (*result != NULL) {
926 return 1;
927 }
928 if (PyErr_Occurred()) {
929 return -1;
930 }
931 return 0;
INADA Naoki378edee2018-01-16 20:52:41 +0900932 }
933 if (tp->tp_getattro != NULL) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200934 *result = (*tp->tp_getattro)(v, name);
INADA Naoki378edee2018-01-16 20:52:41 +0900935 }
936 else if (tp->tp_getattr != NULL) {
937 const char *name_str = PyUnicode_AsUTF8(name);
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200938 if (name_str == NULL) {
939 *result = NULL;
940 return -1;
941 }
942 *result = (*tp->tp_getattr)(v, (char *)name_str);
INADA Naoki378edee2018-01-16 20:52:41 +0900943 }
INADA Naokie76daeb2018-01-26 16:22:51 +0900944 else {
945 *result = NULL;
946 return 0;
947 }
948
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200949 if (*result != NULL) {
950 return 1;
INADA Naoki378edee2018-01-16 20:52:41 +0900951 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200952 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
953 return -1;
954 }
955 PyErr_Clear();
956 return 0;
957}
958
959int
960_PyObject_LookupAttrId(PyObject *v, _Py_Identifier *name, PyObject **result)
961{
962 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
963 if (!oname) {
964 *result = NULL;
965 return -1;
966 }
967 return _PyObject_LookupAttr(v, oname, result);
INADA Naoki378edee2018-01-16 20:52:41 +0900968}
969
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000970int
Fred Drake100814d2000-07-09 15:48:49 +0000971PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000972{
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200973 PyObject *res;
974 if (_PyObject_LookupAttr(v, name, &res) < 0) {
975 PyErr_Clear();
976 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 }
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200978 if (res == NULL) {
979 return 0;
980 }
981 Py_DECREF(res);
982 return 1;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000983}
984
985int
Fred Drake100814d2000-07-09 15:48:49 +0000986PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 PyTypeObject *tp = Py_TYPE(v);
989 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (!PyUnicode_Check(name)) {
992 PyErr_Format(PyExc_TypeError,
993 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +0100994 Py_TYPE(name)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 return -1;
996 }
997 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyUnicode_InternInPlace(&name);
1000 if (tp->tp_setattro != NULL) {
1001 err = (*tp->tp_setattro)(v, name, value);
1002 Py_DECREF(name);
1003 return err;
1004 }
1005 if (tp->tp_setattr != NULL) {
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001006 const char *name_str = PyUnicode_AsUTF8(name);
Zackery Spytze0dcb852019-04-28 06:58:52 -06001007 if (name_str == NULL) {
1008 Py_DECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return -1;
Zackery Spytze0dcb852019-04-28 06:58:52 -06001010 }
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02001011 err = (*tp->tp_setattr)(v, (char *)name_str, value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 Py_DECREF(name);
1013 return err;
1014 }
1015 Py_DECREF(name);
Victor Stinnera93c51e2020-02-07 00:38:59 +01001016 _PyObject_ASSERT(name, Py_REFCNT(name) >= 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1018 PyErr_Format(PyExc_TypeError,
1019 "'%.100s' object has no attributes "
1020 "(%s .%U)",
1021 tp->tp_name,
1022 value==NULL ? "del" : "assign to",
1023 name);
1024 else
1025 PyErr_Format(PyExc_TypeError,
1026 "'%.100s' object has only read-only attributes "
1027 "(%s .%U)",
1028 tp->tp_name,
1029 value==NULL ? "del" : "assign to",
1030 name);
1031 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032}
1033
1034/* Helper to get a pointer to an object's __dict__ slot, if any */
1035
1036PyObject **
1037_PyObject_GetDictPtr(PyObject *obj)
1038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 Py_ssize_t dictoffset;
1040 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 dictoffset = tp->tp_dictoffset;
1043 if (dictoffset == 0)
1044 return NULL;
1045 if (dictoffset < 0) {
Victor Stinnerc65b3202020-02-07 11:18:33 +01001046 Py_ssize_t tsize = Py_SIZE(obj);
1047 if (tsize < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 tsize = -tsize;
Victor Stinnerc65b3202020-02-07 11:18:33 +01001049 }
1050 size_t size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 dictoffset += (long)size;
Victor Stinner24702042018-10-26 17:16:37 +02001053 _PyObject_ASSERT(obj, dictoffset > 0);
1054 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 }
1056 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001057}
1058
Tim Peters6d6c1a32001-08-02 04:15:00 +00001059PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00001060PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +00001061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 Py_INCREF(obj);
1063 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +00001064}
1065
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001066/* Helper used when the __next__ method is removed from a type:
1067 tp_iternext is never NULL and can be safely called without checking
1068 on every iteration.
1069 */
1070
1071PyObject *
1072_PyObject_NextNotImplemented(PyObject *self)
1073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyErr_Format(PyExc_TypeError,
1075 "'%.200s' object is not iterable",
1076 Py_TYPE(self)->tp_name);
1077 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +00001078}
1079
Yury Selivanovf2392132016-12-13 19:03:51 -05001080
1081/* Specialized version of _PyObject_GenericGetAttrWithDict
1082 specifically for the LOAD_METHOD opcode.
1083
1084 Return 1 if a method is found, 0 if it's a regular attribute
1085 from __dict__ or something returned by using a descriptor
1086 protocol.
1087
1088 `method` will point to the resolved attribute or NULL. In the
1089 latter case, an error will be set.
1090*/
1091int
1092_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1093{
1094 PyTypeObject *tp = Py_TYPE(obj);
1095 PyObject *descr;
1096 descrgetfunc f = NULL;
1097 PyObject **dictptr, *dict;
1098 PyObject *attr;
1099 int meth_found = 0;
1100
1101 assert(*method == NULL);
1102
1103 if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
1104 || !PyUnicode_Check(name)) {
1105 *method = PyObject_GetAttr(obj, name);
1106 return 0;
1107 }
1108
1109 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1110 return 0;
1111
1112 descr = _PyType_Lookup(tp, name);
1113 if (descr != NULL) {
1114 Py_INCREF(descr);
Victor Stinner45ec5b92020-04-08 01:42:27 +02001115 if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05001116 meth_found = 1;
1117 } else {
Victor Stinner58ac7002020-02-07 03:04:21 +01001118 f = Py_TYPE(descr)->tp_descr_get;
Yury Selivanovf2392132016-12-13 19:03:51 -05001119 if (f != NULL && PyDescr_IsData(descr)) {
Victor Stinner58ac7002020-02-07 03:04:21 +01001120 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
Yury Selivanovf2392132016-12-13 19:03:51 -05001121 Py_DECREF(descr);
1122 return 0;
1123 }
1124 }
1125 }
1126
1127 dictptr = _PyObject_GetDictPtr(obj);
1128 if (dictptr != NULL && (dict = *dictptr) != NULL) {
1129 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001130 attr = PyDict_GetItemWithError(dict, name);
Yury Selivanovf2392132016-12-13 19:03:51 -05001131 if (attr != NULL) {
1132 Py_INCREF(attr);
1133 *method = attr;
1134 Py_DECREF(dict);
1135 Py_XDECREF(descr);
1136 return 0;
1137 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001138 else {
1139 Py_DECREF(dict);
1140 if (PyErr_Occurred()) {
1141 Py_XDECREF(descr);
1142 return 0;
1143 }
1144 }
Yury Selivanovf2392132016-12-13 19:03:51 -05001145 }
1146
1147 if (meth_found) {
1148 *method = descr;
1149 return 1;
1150 }
1151
1152 if (f != NULL) {
1153 *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1154 Py_DECREF(descr);
1155 return 0;
1156 }
1157
1158 if (descr != NULL) {
1159 *method = descr;
1160 return 0;
1161 }
1162
1163 PyErr_Format(PyExc_AttributeError,
1164 "'%.50s' object has no attribute '%U'",
1165 tp->tp_name, name);
1166 return 0;
1167}
1168
1169/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
Michael W. Hudson1593f502004-09-14 17:09:47 +00001170
Raymond Hettinger01538262003-03-17 08:24:35 +00001171PyObject *
INADA Naoki378edee2018-01-16 20:52:41 +09001172_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1173 PyObject *dict, int suppress)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174{
Yury Selivanovf2392132016-12-13 19:03:51 -05001175 /* Make sure the logic of _PyObject_GetMethod is in sync with
1176 this method.
INADA Naoki378edee2018-01-16 20:52:41 +09001177
Brett Cannond5837382020-07-17 13:09:21 -07001178 When suppress=1, this function suppresses AttributeError.
Yury Selivanovf2392132016-12-13 19:03:51 -05001179 */
1180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 PyTypeObject *tp = Py_TYPE(obj);
1182 PyObject *descr = NULL;
1183 PyObject *res = NULL;
1184 descrgetfunc f;
1185 Py_ssize_t dictoffset;
1186 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (!PyUnicode_Check(name)){
1189 PyErr_Format(PyExc_TypeError,
1190 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +01001191 Py_TYPE(name)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 return NULL;
1193 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001194 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (tp->tp_dict == NULL) {
1197 if (PyType_Ready(tp) < 0)
1198 goto done;
1199 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 descr = _PyType_Lookup(tp, name);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 f = NULL;
1204 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001205 Py_INCREF(descr);
Victor Stinner58ac7002020-02-07 03:04:21 +01001206 f = Py_TYPE(descr)->tp_descr_get;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (f != NULL && PyDescr_IsData(descr)) {
Victor Stinner58ac7002020-02-07 03:04:21 +01001208 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001209 if (res == NULL && suppress &&
1210 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1211 PyErr_Clear();
1212 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 goto done;
1214 }
1215 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001216
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001217 if (dict == NULL) {
1218 /* Inline _PyObject_GetDictPtr */
1219 dictoffset = tp->tp_dictoffset;
1220 if (dictoffset != 0) {
1221 if (dictoffset < 0) {
Victor Stinnerc65b3202020-02-07 11:18:33 +01001222 Py_ssize_t tsize = Py_SIZE(obj);
1223 if (tsize < 0) {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001224 tsize = -tsize;
Victor Stinnerc65b3202020-02-07 11:18:33 +01001225 }
1226 size_t size = _PyObject_VAR_SIZE(tp, tsize);
Victor Stinner24702042018-10-26 17:16:37 +02001227 _PyObject_ASSERT(obj, size <= PY_SSIZE_T_MAX);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001228
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001229 dictoffset += (Py_ssize_t)size;
Victor Stinner24702042018-10-26 17:16:37 +02001230 _PyObject_ASSERT(obj, dictoffset > 0);
1231 _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001233 dictptr = (PyObject **) ((char *)obj + dictoffset);
1234 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 }
1236 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001237 if (dict != NULL) {
1238 Py_INCREF(dict);
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001239 res = PyDict_GetItemWithError(dict, name);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001240 if (res != NULL) {
1241 Py_INCREF(res);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001242 Py_DECREF(dict);
1243 goto done;
1244 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001245 else {
1246 Py_DECREF(dict);
1247 if (PyErr_Occurred()) {
1248 if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1249 PyErr_Clear();
1250 }
1251 else {
1252 goto done;
1253 }
1254 }
1255 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001256 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (f != NULL) {
1259 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
INADA Naoki378edee2018-01-16 20:52:41 +09001260 if (res == NULL && suppress &&
1261 PyErr_ExceptionMatches(PyExc_AttributeError)) {
1262 PyErr_Clear();
1263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 goto done;
1265 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (descr != NULL) {
1268 res = descr;
Victor Stinner2d01dc02012-03-09 00:44:13 +01001269 descr = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 goto done;
1271 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272
INADA Naoki378edee2018-01-16 20:52:41 +09001273 if (!suppress) {
1274 PyErr_Format(PyExc_AttributeError,
1275 "'%.50s' object has no attribute '%U'",
1276 tp->tp_name, name);
1277 }
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001278 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001279 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 Py_DECREF(name);
1281 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001282}
1283
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001284PyObject *
1285PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1286{
INADA Naoki378edee2018-01-16 20:52:41 +09001287 return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001288}
1289
Tim Peters6d6c1a32001-08-02 04:15:00 +00001290int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001291_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1292 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 PyTypeObject *tp = Py_TYPE(obj);
1295 PyObject *descr;
1296 descrsetfunc f;
1297 PyObject **dictptr;
1298 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (!PyUnicode_Check(name)){
1301 PyErr_Format(PyExc_TypeError,
1302 "attribute name must be string, not '%.200s'",
Victor Stinner58ac7002020-02-07 03:04:21 +01001303 Py_TYPE(name)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 return -1;
1305 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001306
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001307 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
1308 return -1;
1309
1310 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 descr = _PyType_Lookup(tp, name);
Victor Stinner2d01dc02012-03-09 00:44:13 +01001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (descr != NULL) {
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001315 Py_INCREF(descr);
Victor Stinner58ac7002020-02-07 03:04:21 +01001316 f = Py_TYPE(descr)->tp_descr_set;
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001317 if (f != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 res = f(descr, obj, value);
1319 goto done;
1320 }
1321 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001322
Steve Dowerb82e17e2019-05-23 08:45:22 -07001323 /* XXX [Steve Dower] These are really noisy - worth it? */
1324 /*if (PyType_Check(obj) || PyModule_Check(obj)) {
1325 if (value && PySys_Audit("object.__setattr__", "OOO", obj, name, value) < 0)
1326 return -1;
1327 if (!value && PySys_Audit("object.__delattr__", "OO", obj, name) < 0)
1328 return -1;
1329 }*/
1330
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001331 if (dict == NULL) {
1332 dictptr = _PyObject_GetDictPtr(obj);
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001333 if (dictptr == NULL) {
1334 if (descr == NULL) {
1335 PyErr_Format(PyExc_AttributeError,
1336 "'%.100s' object has no attribute '%U'",
1337 tp->tp_name, name);
1338 }
1339 else {
1340 PyErr_Format(PyExc_AttributeError,
1341 "'%.50s' object attribute '%U' is read-only",
1342 tp->tp_name, name);
1343 }
Benjamin Peterson7d95e402012-04-23 11:24:50 -04001344 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001346 res = _PyObjectDict_SetItem(tp, dictptr, name, value);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001347 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001348 else {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001349 Py_INCREF(dict);
1350 if (value == NULL)
1351 res = PyDict_DelItem(dict, name);
1352 else
1353 res = PyDict_SetItem(dict, name, value);
Benjamin Peterson74529ad2012-03-09 07:25:32 -08001354 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 }
Serhiy Storchaka55c861f2016-04-17 20:31:51 +03001356 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1357 PyErr_SetObject(PyExc_AttributeError, name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001358
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001359 done:
Victor Stinner2d01dc02012-03-09 00:44:13 +01001360 Py_XDECREF(descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 Py_DECREF(name);
1362 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001363}
1364
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001365int
1366PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1367{
1368 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1369}
1370
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001371int
1372PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
1373{
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001374 PyObject **dictptr = _PyObject_GetDictPtr(obj);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001375 if (dictptr == NULL) {
1376 PyErr_SetString(PyExc_AttributeError,
1377 "This object has no __dict__");
1378 return -1;
1379 }
1380 if (value == NULL) {
1381 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
1382 return -1;
1383 }
1384 if (!PyDict_Check(value)) {
1385 PyErr_Format(PyExc_TypeError,
1386 "__dict__ must be set to a dictionary, "
1387 "not a '%.200s'", Py_TYPE(value)->tp_name);
1388 return -1;
1389 }
Serhiy Storchaka576f1322016-01-05 21:27:54 +02001390 Py_INCREF(value);
Serhiy Storchakaec397562016-04-06 09:50:03 +03001391 Py_XSETREF(*dictptr, value);
Benjamin Peterson8eb12692012-02-19 19:59:10 -05001392 return 0;
1393}
1394
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001395
Stefan Pochmannf90dc362020-10-07 16:12:52 +02001396/* Test a value used as condition, e.g., in a while or if statement.
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001397 Return -1 if an error occurred */
1398
1399int
Fred Drake100814d2000-07-09 15:48:49 +00001400PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 Py_ssize_t res;
1403 if (v == Py_True)
1404 return 1;
1405 if (v == Py_False)
1406 return 0;
1407 if (v == Py_None)
1408 return 0;
Victor Stinner58ac7002020-02-07 03:04:21 +01001409 else if (Py_TYPE(v)->tp_as_number != NULL &&
1410 Py_TYPE(v)->tp_as_number->nb_bool != NULL)
1411 res = (*Py_TYPE(v)->tp_as_number->nb_bool)(v);
1412 else if (Py_TYPE(v)->tp_as_mapping != NULL &&
1413 Py_TYPE(v)->tp_as_mapping->mp_length != NULL)
1414 res = (*Py_TYPE(v)->tp_as_mapping->mp_length)(v);
1415 else if (Py_TYPE(v)->tp_as_sequence != NULL &&
1416 Py_TYPE(v)->tp_as_sequence->sq_length != NULL)
1417 res = (*Py_TYPE(v)->tp_as_sequence->sq_length)(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 else
1419 return 1;
1420 /* if it is negative, it should be either -1 or -2 */
1421 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001422}
1423
Tim Peters803526b2002-07-07 05:13:56 +00001424/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001425 Return -1 if an error occurred */
1426
1427int
Fred Drake100814d2000-07-09 15:48:49 +00001428PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 int res;
1431 res = PyObject_IsTrue(v);
1432 if (res < 0)
1433 return res;
1434 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001435}
1436
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001437/* Test whether an object can be called */
1438
1439int
Fred Drake100814d2000-07-09 15:48:49 +00001440PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (x == NULL)
1443 return 0;
Victor Stinner58ac7002020-02-07 03:04:21 +01001444 return Py_TYPE(x)->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001445}
1446
Tim Peters7eea37e2001-09-04 22:08:56 +00001447
Georg Brandle32b4222007-03-10 22:13:27 +00001448/* Helper for PyObject_Dir without arguments: returns the local scope. */
1449static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001450_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 PyObject *names;
Victor Stinner41bb43a2013-10-29 01:19:37 +01001453 PyObject *locals;
Tim Peters305b5852001-09-17 02:38:46 +00001454
Victor Stinner41bb43a2013-10-29 01:19:37 +01001455 locals = PyEval_GetLocals();
1456 if (locals == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 return NULL;
Tim Peters305b5852001-09-17 02:38:46 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 names = PyMapping_Keys(locals);
1460 if (!names)
1461 return NULL;
1462 if (!PyList_Check(names)) {
1463 PyErr_Format(PyExc_TypeError,
1464 "dir(): expected keys() of locals to be a list, "
1465 "not '%.200s'", Py_TYPE(names)->tp_name);
1466 Py_DECREF(names);
1467 return NULL;
1468 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001469 if (PyList_Sort(names)) {
1470 Py_DECREF(names);
1471 return NULL;
1472 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 /* the locals don't need to be DECREF'd */
1474 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001475}
1476
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001477/* Helper for PyObject_Dir: object introspection. */
Georg Brandle32b4222007-03-10 22:13:27 +00001478static PyObject *
1479_dir_object(PyObject *obj)
1480{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001481 PyObject *result, *sorted;
Benjamin Petersonce798522012-01-22 11:24:29 -05001482 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
Georg Brandle32b4222007-03-10 22:13:27 +00001483
Victor Stinner24702042018-10-26 17:16:37 +02001484 assert(obj != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (dirfunc == NULL) {
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001486 if (!PyErr_Occurred())
1487 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1488 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 }
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001490 /* use __dir__ */
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001491 result = _PyObject_CallNoArg(dirfunc);
Benjamin Peterson82b00c12011-05-24 11:09:06 -05001492 Py_DECREF(dirfunc);
1493 if (result == NULL)
1494 return NULL;
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001495 /* return sorted(result) */
1496 sorted = PySequence_List(result);
1497 Py_DECREF(result);
1498 if (sorted == NULL)
1499 return NULL;
1500 if (PyList_Sort(sorted)) {
1501 Py_DECREF(sorted);
1502 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 }
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001504 return sorted;
Georg Brandle32b4222007-03-10 22:13:27 +00001505}
1506
1507/* Implementation of dir() -- if obj is NULL, returns the names in the current
1508 (local) scope. Otherwise, performs introspection of the object: returns a
1509 sorted list of attribute names (supposedly) accessible from the object
1510*/
1511PyObject *
1512PyObject_Dir(PyObject *obj)
1513{
Benjamin Peterson3bbb7222011-06-11 16:12:08 -05001514 return (obj == NULL) ? _dir_locals() : _dir_object(obj);
Tim Peters7eea37e2001-09-04 22:08:56 +00001515}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001516
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001517/*
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001518None is a non-NULL undefined value.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001519There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001520so there is exactly one (which is indestructible, by the way).
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001521*/
1522
Guido van Rossum0c182a11992-03-27 17:26:13 +00001523/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001524static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001525none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001528}
1529
Barry Warsaw9bf16442001-01-23 16:24:35 +00001530/* ARGUSED */
Victor Stinner2a4903f2020-01-30 13:09:11 +01001531static void _Py_NO_RETURN
Tim Peters803526b2002-07-07 05:13:56 +00001532none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 /* This should never get called, but we also don't want to SEGV if
1535 * we accidentally decref None out of existence.
1536 */
1537 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001538}
1539
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001540static PyObject *
1541none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1542{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001543 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001544 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1545 return NULL;
1546 }
1547 Py_RETURN_NONE;
1548}
1549
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001550static int
1551none_bool(PyObject *v)
1552{
1553 return 0;
1554}
1555
1556static PyNumberMethods none_as_number = {
1557 0, /* nb_add */
1558 0, /* nb_subtract */
1559 0, /* nb_multiply */
1560 0, /* nb_remainder */
1561 0, /* nb_divmod */
1562 0, /* nb_power */
1563 0, /* nb_negative */
1564 0, /* nb_positive */
1565 0, /* nb_absolute */
1566 (inquiry)none_bool, /* nb_bool */
1567 0, /* nb_invert */
1568 0, /* nb_lshift */
1569 0, /* nb_rshift */
1570 0, /* nb_and */
1571 0, /* nb_xor */
1572 0, /* nb_or */
1573 0, /* nb_int */
1574 0, /* nb_reserved */
1575 0, /* nb_float */
1576 0, /* nb_inplace_add */
1577 0, /* nb_inplace_subtract */
1578 0, /* nb_inplace_multiply */
1579 0, /* nb_inplace_remainder */
1580 0, /* nb_inplace_power */
1581 0, /* nb_inplace_lshift */
1582 0, /* nb_inplace_rshift */
1583 0, /* nb_inplace_and */
1584 0, /* nb_inplace_xor */
1585 0, /* nb_inplace_or */
1586 0, /* nb_floor_divide */
1587 0, /* nb_true_divide */
1588 0, /* nb_inplace_floor_divide */
1589 0, /* nb_inplace_true_divide */
1590 0, /* nb_index */
1591};
Barry Warsaw9bf16442001-01-23 16:24:35 +00001592
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001593PyTypeObject _PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1595 "NoneType",
1596 0,
1597 0,
1598 none_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001599 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 0, /*tp_getattr*/
1601 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001602 0, /*tp_as_async*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 none_repr, /*tp_repr*/
Raymond Hettinger66d2be82011-07-28 09:55:13 -07001604 &none_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 0, /*tp_as_sequence*/
1606 0, /*tp_as_mapping*/
1607 0, /*tp_hash */
Benjamin Petersonc4607ae2011-07-29 18:19:43 -05001608 0, /*tp_call */
1609 0, /*tp_str */
1610 0, /*tp_getattro */
1611 0, /*tp_setattro */
1612 0, /*tp_as_buffer */
1613 Py_TPFLAGS_DEFAULT, /*tp_flags */
1614 0, /*tp_doc */
1615 0, /*tp_traverse */
1616 0, /*tp_clear */
1617 0, /*tp_richcompare */
1618 0, /*tp_weaklistoffset */
1619 0, /*tp_iter */
1620 0, /*tp_iternext */
1621 0, /*tp_methods */
1622 0, /*tp_members */
1623 0, /*tp_getset */
1624 0, /*tp_base */
1625 0, /*tp_dict */
1626 0, /*tp_descr_get */
1627 0, /*tp_descr_set */
1628 0, /*tp_dictoffset */
1629 0, /*tp_init */
1630 0, /*tp_alloc */
1631 none_new, /*tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001632};
1633
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001634PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001635 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001636 1, &_PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001637};
1638
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001639/* NotImplemented is an object that can be used to signal that an
1640 operation is not implemented for the given type combination. */
1641
1642static PyObject *
1643NotImplemented_repr(PyObject *op)
1644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001646}
1647
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001648static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301649NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001650{
1651 return PyUnicode_FromString("NotImplemented");
1652}
1653
1654static PyMethodDef notimplemented_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301655 {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001656 {NULL, NULL}
1657};
1658
1659static PyObject *
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001660notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1661{
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001662 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001663 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1664 return NULL;
1665 }
Brian Curtindfc80e32011-08-10 20:28:54 -05001666 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001667}
1668
Victor Stinner2a4903f2020-01-30 13:09:11 +01001669static void _Py_NO_RETURN
Armin Ronacher226b1db2012-10-06 14:28:58 +02001670notimplemented_dealloc(PyObject* ignore)
1671{
1672 /* This should never get called, but we also don't want to SEGV if
1673 * we accidentally decref NotImplemented out of existence.
1674 */
1675 Py_FatalError("deallocating NotImplemented");
1676}
1677
MojoVampire469325c2020-03-03 18:50:17 +00001678static int
1679notimplemented_bool(PyObject *v)
1680{
1681 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1682 "NotImplemented should not be used in a boolean context",
1683 1) < 0)
1684 {
1685 return -1;
1686 }
1687 return 1;
1688}
1689
1690static PyNumberMethods notimplemented_as_number = {
1691 .nb_bool = notimplemented_bool,
1692};
1693
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001694PyTypeObject _PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1696 "NotImplementedType",
1697 0,
1698 0,
Armin Ronacher226b1db2012-10-06 14:28:58 +02001699 notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001700 0, /*tp_vectorcall_offset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 0, /*tp_getattr*/
1702 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001703 0, /*tp_as_async*/
MojoVampire469325c2020-03-03 18:50:17 +00001704 NotImplemented_repr, /*tp_repr*/
1705 &notimplemented_as_number, /*tp_as_number*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 0, /*tp_as_sequence*/
1707 0, /*tp_as_mapping*/
1708 0, /*tp_hash */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001709 0, /*tp_call */
1710 0, /*tp_str */
1711 0, /*tp_getattro */
1712 0, /*tp_setattro */
1713 0, /*tp_as_buffer */
1714 Py_TPFLAGS_DEFAULT, /*tp_flags */
1715 0, /*tp_doc */
1716 0, /*tp_traverse */
1717 0, /*tp_clear */
1718 0, /*tp_richcompare */
1719 0, /*tp_weaklistoffset */
1720 0, /*tp_iter */
1721 0, /*tp_iternext */
Alexandre Vassalottic49477b2013-11-24 02:53:45 -08001722 notimplemented_methods, /*tp_methods */
Benjamin Peterson18d7d7a2011-07-29 18:27:44 -05001723 0, /*tp_members */
1724 0, /*tp_getset */
1725 0, /*tp_base */
1726 0, /*tp_dict */
1727 0, /*tp_descr_get */
1728 0, /*tp_descr_set */
1729 0, /*tp_dictoffset */
1730 0, /*tp_init */
1731 0, /*tp_alloc */
1732 notimplemented_new, /*tp_new */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001733};
1734
1735PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 _PyObject_EXTRA_INIT
Alexandre Vassalotti65846c62013-11-30 17:55:48 -08001737 1, &_PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001738};
1739
Victor Stinner331a6a52019-05-27 16:39:22 +02001740PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01001741_PyTypes_Init(void)
Guido van Rossumba21a492001-08-16 08:17:26 +00001742{
Victor Stinner7a1f6c22020-01-30 09:02:14 +01001743 PyStatus status = _PyTypes_InitSlotDefs();
1744 if (_PyStatus_EXCEPTION(status)) {
1745 return status;
1746 }
1747
Victor Stinnera5180992021-04-08 00:12:38 +02001748#define INIT_TYPE(TYPE) \
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001749 do { \
Victor Stinnera5180992021-04-08 00:12:38 +02001750 if (PyType_Ready(&(TYPE)) < 0) { \
1751 return _PyStatus_ERR("Can't initialize " #TYPE " type"); \
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001752 } \
1753 } while (0)
Victor Stinner5a1bb4e2014-06-02 14:10:59 +02001754
Victor Stinnera5180992021-04-08 00:12:38 +02001755 // Base types
1756 INIT_TYPE(PyBaseObject_Type);
1757 INIT_TYPE(PyType_Type);
1758 assert(PyBaseObject_Type.tp_base == NULL);
1759 assert(PyType_Type.tp_base == &PyBaseObject_Type);
Guido van Rossumba21a492001-08-16 08:17:26 +00001760
Victor Stinnera5180992021-04-08 00:12:38 +02001761 // All other static types
1762 INIT_TYPE(PyBool_Type);
1763 INIT_TYPE(PyByteArray_Type);
1764 INIT_TYPE(PyBytes_Type);
1765 INIT_TYPE(PyCFunction_Type);
1766 INIT_TYPE(PyCMethod_Type);
1767 INIT_TYPE(PyCallIter_Type);
1768 INIT_TYPE(PyCapsule_Type);
1769 INIT_TYPE(PyCell_Type);
1770 INIT_TYPE(PyClassMethodDescr_Type);
1771 INIT_TYPE(PyCode_Type);
1772 INIT_TYPE(PyComplex_Type);
1773 INIT_TYPE(PyCoro_Type);
1774 INIT_TYPE(PyDictItems_Type);
1775 INIT_TYPE(PyDictKeys_Type);
1776 INIT_TYPE(PyDictProxy_Type);
1777 INIT_TYPE(PyDictRevIterItem_Type);
1778 INIT_TYPE(PyDictRevIterKey_Type);
1779 INIT_TYPE(PyDictRevIterValue_Type);
1780 INIT_TYPE(PyDictValues_Type);
1781 INIT_TYPE(PyDict_Type);
1782 INIT_TYPE(PyEllipsis_Type);
1783 INIT_TYPE(PyEnum_Type);
1784 INIT_TYPE(PyFloat_Type);
1785 INIT_TYPE(PyFrame_Type);
1786 INIT_TYPE(PyFrozenSet_Type);
1787 INIT_TYPE(PyFunction_Type);
1788 INIT_TYPE(PyGen_Type);
1789 INIT_TYPE(PyGetSetDescr_Type);
1790 INIT_TYPE(PyInstanceMethod_Type);
1791 INIT_TYPE(PyList_Type);
1792 INIT_TYPE(PyLongRangeIter_Type);
1793 INIT_TYPE(PyLong_Type);
1794 INIT_TYPE(PyMemberDescr_Type);
1795 INIT_TYPE(PyMemoryView_Type);
1796 INIT_TYPE(PyMethodDescr_Type);
1797 INIT_TYPE(PyMethod_Type);
1798 INIT_TYPE(PyODictItems_Type);
1799 INIT_TYPE(PyODictIter_Type);
1800 INIT_TYPE(PyODictKeys_Type);
1801 INIT_TYPE(PyODictValues_Type);
1802 INIT_TYPE(PyODict_Type);
1803 INIT_TYPE(PyPickleBuffer_Type);
1804 INIT_TYPE(PyProperty_Type);
1805 INIT_TYPE(PyRange_Type);
1806 INIT_TYPE(PyReversed_Type);
1807 INIT_TYPE(PySeqIter_Type);
1808 INIT_TYPE(PySet_Type);
1809 INIT_TYPE(PySlice_Type);
1810 INIT_TYPE(PyStaticMethod_Type);
1811 INIT_TYPE(PyStdPrinter_Type);
1812 INIT_TYPE(PySuper_Type);
1813 INIT_TYPE(PyTraceBack_Type);
1814 INIT_TYPE(PyTuple_Type);
1815 INIT_TYPE(PyUnicode_Type);
1816 INIT_TYPE(PyWrapperDescr_Type);
1817 INIT_TYPE(_PyCoroWrapper_Type);
1818 INIT_TYPE(_PyInterpreterID_Type);
1819 INIT_TYPE(_PyManagedBuffer_Type);
1820 INIT_TYPE(_PyMethodWrapper_Type);
1821 INIT_TYPE(_PyNamespace_Type);
1822 INIT_TYPE(_PyNone_Type);
1823 INIT_TYPE(_PyNotImplemented_Type);
1824 INIT_TYPE(_PyWeakref_CallableProxyType);
1825 INIT_TYPE(_PyWeakref_ProxyType);
1826 INIT_TYPE(_PyWeakref_RefType);
1827
1828 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001829#undef INIT_TYPE
Guido van Rossumba21a492001-08-16 08:17:26 +00001830}
1831
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001832
Victor Stinner40e547d2020-02-05 01:11:10 +01001833void
1834_Py_NewReference(PyObject *op)
1835{
1836 if (_Py_tracemalloc_config.tracing) {
1837 _PyTraceMalloc_NewReference(op);
1838 }
1839#ifdef Py_REF_DEBUG
1840 _Py_RefTotal++;
1841#endif
Victor Stinnerc86a1122020-02-07 01:24:29 +01001842 Py_SET_REFCNT(op, 1);
Victor Stinner40e547d2020-02-05 01:11:10 +01001843#ifdef Py_TRACE_REFS
1844 _Py_AddToAllObjects(op, 1);
1845#endif
1846}
1847
1848
Guido van Rossum84a90321996-05-22 16:34:47 +00001849#ifdef Py_TRACE_REFS
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001850void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001851_Py_ForgetReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001852{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001853 if (Py_REFCNT(op) < 0) {
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001854 _PyObject_ASSERT_FAILED_MSG(op, "negative refcnt");
1855 }
1856
1857 if (op == &refchain ||
1858 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
1859 {
1860 _PyObject_ASSERT_FAILED_MSG(op, "invalid object chain");
1861 }
1862
Guido van Rossumbffd6832000-01-20 22:32:56 +00001863#ifdef SLOW_UNREF_CHECK
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001864 PyObject *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001866 if (p == op) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 break;
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 }
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001870 if (p == &refchain) {
1871 /* Not found */
1872 _PyObject_ASSERT_FAILED_MSG(op,
1873 "object not found in the objects list");
1874 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001875#endif
Victor Stinner5eb8bff2020-01-30 09:01:07 +01001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 op->_ob_next->_ob_prev = op->_ob_prev;
1878 op->_ob_prev->_ob_next = op->_ob_next;
1879 op->_ob_next = op->_ob_prev = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001880}
1881
Tim Peters269b2a62003-04-17 19:52:29 +00001882/* Print all live objects. Because PyObject_Print is called, the
1883 * interpreter must be in a healthy state.
1884 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001885void
Fred Drake100814d2000-07-09 15:48:49 +00001886_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 PyObject *op;
1889 fprintf(fp, "Remaining objects:\n");
1890 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
Victor Stinnerd36cf5f2020-06-10 18:38:05 +02001891 fprintf(fp, "%p [%zd] ", (void *)op, Py_REFCNT(op));
1892 if (PyObject_Print(op, fp, 0) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyErr_Clear();
Victor Stinnerd36cf5f2020-06-10 18:38:05 +02001894 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 putc('\n', fp);
1896 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001897}
1898
Tim Peters269b2a62003-04-17 19:52:29 +00001899/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1900 * doesn't make any calls to the Python C API, so is always safe to call.
1901 */
1902void
1903_Py_PrintReferenceAddresses(FILE *fp)
1904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 PyObject *op;
1906 fprintf(fp, "Remaining object addresses:\n");
1907 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
Victor Stinnerd36cf5f2020-06-10 18:38:05 +02001908 fprintf(fp, "%p [%zd] %s\n", (void *)op,
Victor Stinnera93c51e2020-02-07 00:38:59 +01001909 Py_REFCNT(op), Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001910}
1911
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001912PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001913_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 int i, n;
1916 PyObject *t = NULL;
1917 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1920 return NULL;
1921 op = refchain._ob_next;
1922 res = PyList_New(0);
1923 if (res == NULL)
1924 return NULL;
1925 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1926 while (op == self || op == args || op == res || op == t ||
Andy Lester55728702020-03-06 16:53:17 -06001927 (t != NULL && !Py_IS_TYPE(op, (PyTypeObject *) t))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 op = op->_ob_next;
1929 if (op == &refchain)
1930 return res;
1931 }
1932 if (PyList_Append(res, op) < 0) {
1933 Py_DECREF(res);
1934 return NULL;
1935 }
1936 op = op->_ob_next;
1937 }
1938 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001939}
1940
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001941#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001942
Benjamin Petersonb173f782009-05-05 22:31:58 +00001943
Guido van Rossum84a90321996-05-22 16:34:47 +00001944/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001945Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001946
1947
David Malcolm49526f42012-06-22 14:55:41 -04001948void
1949_PyObject_DebugTypeStats(FILE *out)
1950{
David Malcolm49526f42012-06-22 14:55:41 -04001951 _PyDict_DebugMallocStats(out);
1952 _PyFloat_DebugMallocStats(out);
1953 _PyFrame_DebugMallocStats(out);
1954 _PyList_DebugMallocStats(out);
David Malcolm49526f42012-06-22 14:55:41 -04001955 _PyTuple_DebugMallocStats(out);
1956}
Guido van Rossumb18618d2000-05-03 23:44:39 +00001957
Guido van Rossum86610361998-04-10 22:32:46 +00001958/* These methods are used to control infinite recursion in repr, str, print,
1959 etc. Container objects that may recursively contain themselves,
Martin Panter8d56c022016-05-29 04:13:35 +00001960 e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
Guido van Rossum86610361998-04-10 22:32:46 +00001961 Py_ReprLeave() to avoid infinite recursion.
1962
1963 Py_ReprEnter() returns 0 the first time it is called for a particular
1964 object and 1 every time thereafter. It returns -1 if an exception
1965 occurred. Py_ReprLeave() has no return value.
1966
1967 See dictobject.c and listobject.c for examples of use.
1968*/
1969
Guido van Rossum86610361998-04-10 22:32:46 +00001970int
Fred Drake100814d2000-07-09 15:48:49 +00001971Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 PyObject *dict;
1974 PyObject *list;
1975 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 dict = PyThreadState_GetDict();
Antoine Pitrou04d17d32014-03-31 22:04:38 +02001978 /* Ignore a missing thread-state, so that this function can be called
1979 early on startup. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (dict == NULL)
1981 return 0;
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001982 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (list == NULL) {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02001984 if (PyErr_Occurred()) {
1985 return -1;
1986 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 list = PyList_New(0);
1988 if (list == NULL)
1989 return -1;
Victor Stinner7a07e452013-11-06 18:57:29 +01001990 if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 return -1;
1992 Py_DECREF(list);
1993 }
1994 i = PyList_GET_SIZE(list);
1995 while (--i >= 0) {
1996 if (PyList_GET_ITEM(list, i) == obj)
1997 return 1;
1998 }
Victor Stinnere901d1f2013-07-17 21:58:41 +02001999 if (PyList_Append(list, obj) < 0)
2000 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00002002}
2003
2004void
Fred Drake100814d2000-07-09 15:48:49 +00002005Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 PyObject *dict;
2008 PyObject *list;
2009 Py_ssize_t i;
Victor Stinner1b634932013-07-16 22:24:44 +02002010 PyObject *error_type, *error_value, *error_traceback;
2011
2012 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 dict = PyThreadState_GetDict();
2015 if (dict == NULL)
Victor Stinner1b634932013-07-16 22:24:44 +02002016 goto finally;
2017
Serhiy Storchakaa24107b2019-02-25 17:59:46 +02002018 list = _PyDict_GetItemIdWithError(dict, &PyId_Py_Repr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 if (list == NULL || !PyList_Check(list))
Victor Stinner1b634932013-07-16 22:24:44 +02002020 goto finally;
2021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 i = PyList_GET_SIZE(list);
2023 /* Count backwards because we always expect obj to be list[-1] */
2024 while (--i >= 0) {
2025 if (PyList_GET_ITEM(list, i) == obj) {
2026 PyList_SetSlice(list, i, i + 1, NULL);
2027 break;
2028 }
2029 }
Victor Stinner1b634932013-07-16 22:24:44 +02002030
2031finally:
2032 /* ignore exceptions because there is no way to report them. */
2033 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossum86610361998-04-10 22:32:46 +00002034}
Guido van Rossumd724b232000-03-13 16:01:29 +00002035
Tim Peters803526b2002-07-07 05:13:56 +00002036/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00002037
Tim Peters803526b2002-07-07 05:13:56 +00002038/* Add op to the _PyTrash_delete_later list. Called when the current
2039 * call-stack depth gets large. op must be a currently untracked gc'ed
2040 * object, with refcount 0. Py_DECREF must already have been called on it.
2041 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002042void
Fred Drake100814d2000-07-09 15:48:49 +00002043_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00002044{
Victor Stinner1bcc32f2020-06-10 20:08:26 +02002045 PyInterpreterState *interp = _PyInterpreterState_GET();
2046 struct _gc_runtime_state *gcstate = &interp->gc;
Victor Stinner72474072019-11-20 12:25:50 +01002047
Hai Shi675d9a32020-04-15 02:11:20 +08002048 _PyObject_ASSERT(op, _PyObject_IS_GC(op));
Victor Stinner24702042018-10-26 17:16:37 +02002049 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
Victor Stinnera93c51e2020-02-07 00:38:59 +01002050 _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
Victor Stinner72474072019-11-20 12:25:50 +01002051 _PyGCHead_SET_PREV(_Py_AS_GC(op), gcstate->trash_delete_later);
2052 gcstate->trash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00002053}
2054
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002055/* The equivalent API, using per-thread state recursion info */
2056void
2057_PyTrash_thread_deposit_object(PyObject *op)
2058{
Victor Stinner50b48572018-11-01 01:51:40 +01002059 PyThreadState *tstate = _PyThreadState_GET();
Hai Shi675d9a32020-04-15 02:11:20 +08002060 _PyObject_ASSERT(op, _PyObject_IS_GC(op));
Victor Stinner24702042018-10-26 17:16:37 +02002061 _PyObject_ASSERT(op, !_PyObject_GC_IS_TRACKED(op));
Victor Stinnera93c51e2020-02-07 00:38:59 +01002062 _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002063 _PyGCHead_SET_PREV(_Py_AS_GC(op), tstate->trash_delete_later);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002064 tstate->trash_delete_later = op;
2065}
2066
Min ho Kimc4cacc82019-07-31 08:16:13 +10002067/* Deallocate all the objects in the _PyTrash_delete_later list. Called when
Tim Peters803526b2002-07-07 05:13:56 +00002068 * the call-stack unwinds again.
2069 */
Guido van Rossumd724b232000-03-13 16:01:29 +00002070void
Fred Drake100814d2000-07-09 15:48:49 +00002071_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00002072{
Victor Stinner1bcc32f2020-06-10 20:08:26 +02002073 PyInterpreterState *interp = _PyInterpreterState_GET();
2074 struct _gc_runtime_state *gcstate = &interp->gc;
Victor Stinner72474072019-11-20 12:25:50 +01002075
2076 while (gcstate->trash_delete_later) {
2077 PyObject *op = gcstate->trash_delete_later;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00002079
Victor Stinner72474072019-11-20 12:25:50 +01002080 gcstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002081 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Neil Schemenauerf589c052002-03-29 03:05:54 +00002082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 /* Call the deallocator directly. This used to try to
2084 * fool Py_DECREF into calling it indirectly, but
2085 * Py_DECREF was already called on this object, and in
2086 * assorted non-release builds calling Py_DECREF again ends
2087 * up distorting allocation statistics.
2088 */
Victor Stinnera93c51e2020-02-07 00:38:59 +01002089 _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
Victor Stinner72474072019-11-20 12:25:50 +01002090 ++gcstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 (*dealloc)(op);
Victor Stinner72474072019-11-20 12:25:50 +01002092 --gcstate->trash_delete_nesting;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 }
Guido van Rossumd724b232000-03-13 16:01:29 +00002094}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002095
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002096/* The equivalent API, using per-thread state recursion info */
2097void
2098_PyTrash_thread_destroy_chain(void)
2099{
Victor Stinner50b48572018-11-01 01:51:40 +01002100 PyThreadState *tstate = _PyThreadState_GET();
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002101 /* We need to increase trash_delete_nesting here, otherwise,
2102 _PyTrash_thread_destroy_chain will be called recursively
2103 and then possibly crash. An example that may crash without
2104 increase:
2105 N = 500000 # need to be large enough
2106 ob = object()
2107 tups = [(ob,) for i in range(N)]
2108 for i in range(49):
2109 tups = [(tup,) for tup in tups]
2110 del tups
2111 */
2112 assert(tstate->trash_delete_nesting == 0);
2113 ++tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002114 while (tstate->trash_delete_later) {
2115 PyObject *op = tstate->trash_delete_later;
2116 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2117
2118 tstate->trash_delete_later =
INADA Naoki5ac9e6e2018-07-10 17:19:53 +09002119 (PyObject*) _PyGCHead_PREV(_Py_AS_GC(op));
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002120
2121 /* Call the deallocator directly. This used to try to
2122 * fool Py_DECREF into calling it indirectly, but
2123 * Py_DECREF was already called on this object, and in
2124 * assorted non-release builds calling Py_DECREF again ends
2125 * up distorting allocation statistics.
2126 */
Victor Stinnera93c51e2020-02-07 00:38:59 +01002127 _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002128 (*dealloc)(op);
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002129 assert(tstate->trash_delete_nesting == 1);
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002130 }
Xiang Zhanga66f9c62017-05-13 13:36:14 +08002131 --tstate->trash_delete_nesting;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +02002132}
2133
Victor Stinner626bff82018-10-25 17:31:10 +02002134
Victor Stinner38965ec2020-03-13 16:51:52 +01002135int
2136_PyTrash_begin(PyThreadState *tstate, PyObject *op)
2137{
2138 if (tstate->trash_delete_nesting >= PyTrash_UNWIND_LEVEL) {
2139 /* Store the object (to be deallocated later) and jump past
2140 * Py_TRASHCAN_END, skipping the body of the deallocator */
2141 _PyTrash_thread_deposit_object(op);
2142 return 1;
2143 }
2144 ++tstate->trash_delete_nesting;
2145 return 0;
2146}
2147
2148
2149void
2150_PyTrash_end(PyThreadState *tstate)
2151{
2152 --tstate->trash_delete_nesting;
2153 if (tstate->trash_delete_later && tstate->trash_delete_nesting <= 0) {
2154 _PyTrash_thread_destroy_chain();
2155 }
2156}
2157
2158
Hai Shied1a5a52020-11-25 06:03:31 +08002159/* bpo-40170: It's only be used in Py_TRASHCAN_BEGIN macro to hide
2160 implementation details. */
2161int
2162_PyTrash_cond(PyObject *op, destructor dealloc)
2163{
2164 return Py_TYPE(op)->tp_dealloc == dealloc;
2165}
2166
2167
Victor Stinner2a4903f2020-01-30 13:09:11 +01002168void _Py_NO_RETURN
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002169_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
Victor Stinner626bff82018-10-25 17:31:10 +02002170 const char *file, int line, const char *function)
2171{
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002172 fprintf(stderr, "%s:%d: ", file, line);
2173 if (function) {
2174 fprintf(stderr, "%s: ", function);
2175 }
Victor Stinner626bff82018-10-25 17:31:10 +02002176 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002177
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002178 if (expr) {
2179 fprintf(stderr, "Assertion \"%s\" failed", expr);
Victor Stinner626bff82018-10-25 17:31:10 +02002180 }
2181 else {
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002182 fprintf(stderr, "Assertion failed");
Victor Stinner626bff82018-10-25 17:31:10 +02002183 }
2184 fflush(stderr);
Victor Stinner68762572019-10-07 18:42:01 +02002185
Victor Stinnerf1d002c2018-11-21 23:53:44 +01002186 if (msg) {
2187 fprintf(stderr, ": %s", msg);
2188 }
2189 fprintf(stderr, "\n");
2190 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002191
Victor Stinner68762572019-10-07 18:42:01 +02002192 if (_PyObject_IsFreed(obj)) {
Victor Stinner626bff82018-10-25 17:31:10 +02002193 /* It seems like the object memory has been freed:
2194 don't access it to prevent a segmentation fault. */
Victor Stinnerb39afb72019-09-17 23:36:28 +02002195 fprintf(stderr, "<object at %p is freed>\n", obj);
Victor Stinner68762572019-10-07 18:42:01 +02002196 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002197 }
2198 else {
penguindustin96466302019-05-06 14:57:17 -04002199 /* Display the traceback where the object has been allocated.
Victor Stinner626bff82018-10-25 17:31:10 +02002200 Do it before dumping repr(obj), since repr() is more likely
2201 to crash than dumping the traceback. */
2202 void *ptr;
2203 PyTypeObject *type = Py_TYPE(obj);
Victor Stinner45ec5b92020-04-08 01:42:27 +02002204 if (_PyType_IS_GC(type)) {
Victor Stinner626bff82018-10-25 17:31:10 +02002205 ptr = (void *)((char *)obj - sizeof(PyGC_Head));
2206 }
2207 else {
2208 ptr = (void *)obj;
2209 }
2210 _PyMem_DumpTraceback(fileno(stderr), ptr);
2211
2212 /* This might succeed or fail, but we're about to abort, so at least
2213 try to provide any extra info we can: */
2214 _PyObject_Dump(obj);
Victor Stinner77753492019-10-07 23:44:05 +02002215
2216 fprintf(stderr, "\n");
2217 fflush(stderr);
Victor Stinner626bff82018-10-25 17:31:10 +02002218 }
Victor Stinner626bff82018-10-25 17:31:10 +02002219
2220 Py_FatalError("_PyObject_AssertFailed");
2221}
2222
Victor Stinner3c09dca2018-10-30 14:48:26 +01002223
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002224void
2225_Py_Dealloc(PyObject *op)
2226{
Victor Stinner3c09dca2018-10-30 14:48:26 +01002227 destructor dealloc = Py_TYPE(op)->tp_dealloc;
2228#ifdef Py_TRACE_REFS
2229 _Py_ForgetReference(op);
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002230#endif
Victor Stinner3c09dca2018-10-30 14:48:26 +01002231 (*dealloc)(op);
2232}
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002233
Victor Stinner38aefc52020-04-06 14:07:02 +02002234
2235PyObject **
2236PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
2237{
2238 return _PyObject_GET_WEAKREFS_LISTPTR(op);
2239}
2240
2241
Victor Stinner53a03aa2020-11-05 15:02:12 +01002242#undef Py_NewRef
2243#undef Py_XNewRef
2244
2245// Export Py_NewRef() and Py_XNewRef() as regular functions for the stable ABI.
2246PyObject*
2247Py_NewRef(PyObject *obj)
2248{
2249 return _Py_NewRef(obj);
2250}
2251
2252PyObject*
2253Py_XNewRef(PyObject *obj)
2254{
2255 return _Py_XNewRef(obj);
2256}
2257
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002258#ifdef __cplusplus
2259}
2260#endif