blob: 4730a66659c734e549ae84948bb4b2a30d055320 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Generic object operations; and implementation of None (NoObject) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00005#include "frameobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007#ifdef __cplusplus
8extern "C" {
9#endif
10
Tim Peters34592512002-07-11 06:23:50 +000011#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000012Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013
14Py_ssize_t
15_Py_GetRefTotal(void)
16{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017 PyObject *o;
18 Py_ssize_t total = _Py_RefTotal;
19 /* ignore the references to the dummy object of the dicts and sets
20 because they are not reliable and not useful (now that the
21 hash table code is well-tested) */
22 o = _PyDict_Dummy();
23 if (o != NULL)
24 total -= o->ob_refcnt;
25 o = _PySet_Dummy();
26 if (o != NULL)
27 total -= o->ob_refcnt;
28 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000029}
30#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031
Mark Hammonda2905272002-07-29 13:42:14 +000032int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000033
Guido van Rossum3f5da241990-12-20 15:06:42 +000034/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
35 These are used by the individual routines for object creation.
36 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037
Tim Peters78be7992003-03-23 02:51:01 +000038#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000039/* Head of circular doubly-linked list of all objects. These are linked
40 * together via the _ob_prev and _ob_next members of a PyObject, which
41 * exist only in a Py_TRACE_REFS build.
42 */
Tim Peters78be7992003-03-23 02:51:01 +000043static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000044
Tim Peters7571a0f2003-03-23 17:52:28 +000045/* Insert op at the front of the list of all objects. If force is true,
46 * op is added even if _ob_prev and _ob_next are non-NULL already. If
47 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
48 * force should be true if and only if op points to freshly allocated,
49 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000050 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000051 * Note that objects are normally added to the list via _Py_NewReference,
52 * which is called by PyObject_Init. Not all objects are initialized that
53 * way, though; exceptions include statically allocated type objects, and
54 * statically allocated singletons (like Py_True and Py_None).
55 */
Tim Peters36eb4df2003-03-23 03:33:13 +000056void
Tim Peters7571a0f2003-03-23 17:52:28 +000057_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000058{
Tim Peters7571a0f2003-03-23 17:52:28 +000059#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 if (!force) {
61 /* If it's initialized memory, op must be in or out of
62 * the list unambiguously.
63 */
64 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
65 }
Tim Peters78be7992003-03-23 02:51:01 +000066#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 if (force || op->_ob_prev == NULL) {
68 op->_ob_next = refchain._ob_next;
69 op->_ob_prev = &refchain;
70 refchain._ob_next->_ob_prev = op;
71 refchain._ob_next = op;
72 }
Tim Peters7571a0f2003-03-23 17:52:28 +000073}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000075
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078/* All types are added to type_list, at least when
79 they get one object created. That makes them
80 immortal, which unfortunately contributes to
81 garbage itself. If unlist_types_without_objects
82 is set, they will be removed from the type_list
83 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +000084static int unlist_types_without_objects;
85extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
86extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
87extern Py_ssize_t null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000088void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 for (tp = type_list; tp; tp = tp->tp_next)
94 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
95 "freed: %" PY_FORMAT_SIZE_T "d, "
96 "max in use: %" PY_FORMAT_SIZE_T "d\n",
97 tp->tp_name, tp->tp_allocs, tp->tp_frees,
98 tp->tp_maxalloc);
99 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
100 "empty: %" PY_FORMAT_SIZE_T "d\n",
101 fast_tuple_allocs, tuple_zero_allocs);
102 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
103 "neg: %" PY_FORMAT_SIZE_T "d\n",
104 quick_int_allocs, quick_neg_int_allocs);
105 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
106 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
107 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000108}
109
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000110PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000111get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PyTypeObject *tp;
114 PyObject *result;
115 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 result = PyList_New(0);
118 if (result == NULL)
119 return NULL;
120 for (tp = type_list; tp; tp = tp->tp_next) {
121 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
122 tp->tp_frees, tp->tp_maxalloc);
123 if (v == NULL) {
124 Py_DECREF(result);
125 return NULL;
126 }
127 if (PyList_Append(result, v) < 0) {
128 Py_DECREF(v);
129 Py_DECREF(result);
130 return NULL;
131 }
132 Py_DECREF(v);
133 }
134 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000135}
136
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000137void
Fred Drake100814d2000-07-09 15:48:49 +0000138inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
141 /* first time; insert in linked list */
142 if (tp->tp_next != NULL) /* sanity check */
143 Py_FatalError("XXX inc_count sanity check");
144 if (type_list)
145 type_list->tp_prev = tp;
146 tp->tp_next = type_list;
147 /* Note that as of Python 2.2, heap-allocated type objects
148 * can go away, but this code requires that they stay alive
149 * until program exit. That's why we're careful with
150 * refcounts here. type_list gets a new reference to tp,
151 * while ownership of the reference type_list used to hold
152 * (if any) was transferred to tp->tp_next in the line above.
153 * tp is thus effectively immortal after this.
154 */
155 Py_INCREF(tp);
156 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000157#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 /* Also insert in the doubly-linked list of all objects,
159 * if not already there.
160 */
161 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000162#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
164 tp->tp_allocs++;
165 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
166 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000167}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000168
169void dec_count(PyTypeObject *tp)
170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 tp->tp_frees++;
172 if (unlist_types_without_objects &&
173 tp->tp_allocs == tp->tp_frees) {
174 /* unlink the type from type_list */
175 if (tp->tp_prev)
176 tp->tp_prev->tp_next = tp->tp_next;
177 else
178 type_list = tp->tp_next;
179 if (tp->tp_next)
180 tp->tp_next->tp_prev = tp->tp_prev;
181 tp->tp_next = tp->tp_prev = NULL;
182 Py_DECREF(tp);
183 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184}
185
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000186#endif
187
Tim Peters7c321a82002-07-09 02:57:01 +0000188#ifdef Py_REF_DEBUG
189/* Log a fatal error; doesn't return. */
190void
191_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyOS_snprintf(buf, sizeof(buf),
196 "%s:%i object at %p has negative ref count "
197 "%" PY_FORMAT_SIZE_T "d",
198 fname, lineno, op, op->ob_refcnt);
199 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000200}
201
202#endif /* Py_REF_DEBUG */
203
Thomas Heller1328b522004-04-22 17:23:49 +0000204void
205Py_IncRef(PyObject *o)
206{
207 Py_XINCREF(o);
208}
209
210void
211Py_DecRef(PyObject *o)
212{
213 Py_XDECREF(o);
214}
215
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000216PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000217PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 if (op == NULL)
220 return PyErr_NoMemory();
221 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
222 Py_TYPE(op) = tp;
223 _Py_NewReference(op);
224 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225}
226
Guido van Rossumb18618d2000-05-03 23:44:39 +0000227PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000228PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (op == NULL)
231 return (PyVarObject *) PyErr_NoMemory();
232 /* Any changes should be reflected in PyObject_INIT_VAR */
233 op->ob_size = size;
234 Py_TYPE(op) = tp;
235 _Py_NewReference((PyObject *)op);
236 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000237}
238
239PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000240_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyObject *op;
243 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
244 if (op == NULL)
245 return PyErr_NoMemory();
246 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000247}
248
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000249PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000250_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 PyVarObject *op;
253 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
254 op = (PyVarObject *) PyObject_MALLOC(size);
255 if (op == NULL)
256 return (PyVarObject *)PyErr_NoMemory();
257 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000258}
259
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000260int
261PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (PyErr_CheckSignals())
265 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000266#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (PyOS_CheckStack()) {
268 PyErr_SetString(PyExc_MemoryError, "stack overflow");
269 return -1;
270 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000271#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 clearerr(fp); /* Clear any previous error condition */
273 if (op == NULL) {
274 Py_BEGIN_ALLOW_THREADS
275 fprintf(fp, "<nil>");
276 Py_END_ALLOW_THREADS
277 }
278 else {
279 if (op->ob_refcnt <= 0)
280 /* XXX(twouters) cast refcount to long until %zd is
281 universally available */
282 Py_BEGIN_ALLOW_THREADS
283 fprintf(fp, "<refcnt %ld at %p>",
284 (long)op->ob_refcnt, op);
285 Py_END_ALLOW_THREADS
286 else {
287 PyObject *s;
288 if (flags & Py_PRINT_RAW)
289 s = PyObject_Str(op);
290 else
291 s = PyObject_Repr(op);
292 if (s == NULL)
293 ret = -1;
294 else if (PyBytes_Check(s)) {
295 fwrite(PyBytes_AS_STRING(s), 1,
296 PyBytes_GET_SIZE(s), fp);
297 }
298 else if (PyUnicode_Check(s)) {
299 PyObject *t;
Victor Stinner372ac5e2010-05-17 01:26:01 +0000300 t = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(s),
301 PyUnicode_GET_SIZE(s),
302 "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (t == NULL)
304 ret = 0;
305 else {
306 fwrite(PyBytes_AS_STRING(t), 1,
307 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000308 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 }
310 }
311 else {
312 PyErr_Format(PyExc_TypeError,
313 "str() or repr() returned '%.100s'",
314 s->ob_type->tp_name);
315 ret = -1;
316 }
317 Py_XDECREF(s);
318 }
319 }
320 if (ret == 0) {
321 if (ferror(fp)) {
322 PyErr_SetFromErrno(PyExc_IOError);
323 clearerr(fp);
324 ret = -1;
325 }
326 }
327 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000328}
329
Guido van Rossum38938152006-08-21 23:36:26 +0000330/* For debugging convenience. Set a breakpoint here and call it from your DLL */
331void
Thomas Woutersb2137042007-02-01 18:02:27 +0000332_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000333{
334}
335
Neal Norwitz1a997502003-01-13 20:13:12 +0000336
Barry Warsaw9bf16442001-01-23 16:24:35 +0000337/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000338void
339_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (op == NULL)
342 fprintf(stderr, "NULL\n");
343 else {
Georg Brandldfd73442009-04-05 11:47:34 +0000344#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 PyGILState_STATE gil;
Georg Brandldfd73442009-04-05 11:47:34 +0000346#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 fprintf(stderr, "object : ");
Georg Brandldfd73442009-04-05 11:47:34 +0000348#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 gil = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000350#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 (void)PyObject_Print(op, stderr, 0);
Georg Brandldfd73442009-04-05 11:47:34 +0000352#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyGILState_Release(gil);
Georg Brandldfd73442009-04-05 11:47:34 +0000354#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* XXX(twouters) cast refcount to long until %zd is
356 universally available */
357 fprintf(stderr, "\n"
358 "type : %s\n"
359 "refcount: %ld\n"
360 "address : %p\n",
361 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
362 (long)op->ob_refcnt,
363 op);
364 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000365}
Barry Warsaw903138f2001-01-23 16:33:18 +0000366
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000368PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyObject *res;
371 if (PyErr_CheckSignals())
372 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000373#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (PyOS_CheckStack()) {
375 PyErr_SetString(PyExc_MemoryError, "stack overflow");
376 return NULL;
377 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000378#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (v == NULL)
380 return PyUnicode_FromString("<NULL>");
381 if (Py_TYPE(v)->tp_repr == NULL)
382 return PyUnicode_FromFormat("<%s object at %p>",
383 v->ob_type->tp_name, v);
384 res = (*v->ob_type->tp_repr)(v);
385 if (res != NULL && !PyUnicode_Check(res)) {
386 PyErr_Format(PyExc_TypeError,
387 "__repr__ returned non-string (type %.200s)",
388 res->ob_type->tp_name);
389 Py_DECREF(res);
390 return NULL;
391 }
392 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393}
394
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000396PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 PyObject *res;
399 if (PyErr_CheckSignals())
400 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000401#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (PyOS_CheckStack()) {
403 PyErr_SetString(PyExc_MemoryError, "stack overflow");
404 return NULL;
405 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000406#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (v == NULL)
408 return PyUnicode_FromString("<NULL>");
409 if (PyUnicode_CheckExact(v)) {
410 Py_INCREF(v);
411 return v;
412 }
413 if (Py_TYPE(v)->tp_str == NULL)
414 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 /* It is possible for a type to have a tp_str representation that loops
417 infinitely. */
418 if (Py_EnterRecursiveCall(" while getting the str of an object"))
419 return NULL;
420 res = (*Py_TYPE(v)->tp_str)(v);
421 Py_LeaveRecursiveCall();
422 if (res == NULL)
423 return NULL;
424 if (!PyUnicode_Check(res)) {
425 PyErr_Format(PyExc_TypeError,
426 "__str__ returned non-string (type %.200s)",
427 Py_TYPE(res)->tp_name);
428 Py_DECREF(res);
429 return NULL;
430 }
431 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000432}
433
Georg Brandl559e5d72008-06-11 18:37:52 +0000434PyObject *
435PyObject_ASCII(PyObject *v)
436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 repr = PyObject_Repr(v);
440 if (repr == NULL)
441 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
444 ascii = PyUnicode_EncodeASCII(
445 PyUnicode_AS_UNICODE(repr),
446 PyUnicode_GET_SIZE(repr),
447 "backslashreplace");
Georg Brandl559e5d72008-06-11 18:37:52 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 Py_DECREF(repr);
450 if (ascii == NULL)
451 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 res = PyUnicode_DecodeASCII(
454 PyBytes_AS_STRING(ascii),
455 PyBytes_GET_SIZE(ascii),
456 NULL);
457
458 Py_DECREF(ascii);
459 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000460}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000461
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000462PyObject *
463PyObject_Bytes(PyObject *v)
464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 PyObject *result, *func;
466 static PyObject *bytesstring = NULL;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (v == NULL)
469 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (PyBytes_CheckExact(v)) {
472 Py_INCREF(v);
473 return v;
474 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring);
477 if (func != NULL) {
478 result = PyObject_CallFunctionObjArgs(func, NULL);
479 Py_DECREF(func);
480 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000481 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000483 PyErr_Format(PyExc_TypeError,
484 "__bytes__ returned non-bytes (type %.200s)",
485 Py_TYPE(result)->tp_name);
486 Py_DECREF(result);
487 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 }
489 return result;
490 }
491 else if (PyErr_Occurred())
492 return NULL;
493 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000494}
495
Mark Dickinsonc008a172009-02-01 13:59:22 +0000496/* For Python 3.0.1 and later, the old three-way comparison has been
497 completely removed in favour of rich comparisons. PyObject_Compare() and
498 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000499 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000500 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000501
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000502 See (*) below for practical amendments.
503
Mark Dickinsonc008a172009-02-01 13:59:22 +0000504 tp_richcompare gets called with a first argument of the appropriate type
505 and a second object of an arbitrary type. We never do any kind of
506 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000507
Mark Dickinsonc008a172009-02-01 13:59:22 +0000508 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000509
510 NULL if an exception occurred
511 NotImplemented if the requested comparison is not implemented
512 any other false value if the requested comparison is false
513 any other true value if the requested comparison is true
514
515 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
516 NotImplemented.
517
518 (*) Practical amendments:
519
520 - If rich comparison returns NotImplemented, == and != are decided by
521 comparing the object pointer (i.e. falling back to the base object
522 implementation).
523
Guido van Rossuma4073002002-05-31 20:03:54 +0000524*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000525
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000526/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000527int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000528
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000529static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000530
531/* Perform a rich comparison, raising TypeError when the requested comparison
532 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000533static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000534do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 richcmpfunc f;
537 PyObject *res;
538 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 if (v->ob_type != w->ob_type &&
541 PyType_IsSubtype(w->ob_type, v->ob_type) &&
542 (f = w->ob_type->tp_richcompare) != NULL) {
543 checked_reverse_op = 1;
544 res = (*f)(w, v, _Py_SwappedOp[op]);
545 if (res != Py_NotImplemented)
546 return res;
547 Py_DECREF(res);
548 }
549 if ((f = v->ob_type->tp_richcompare) != NULL) {
550 res = (*f)(v, w, op);
551 if (res != Py_NotImplemented)
552 return res;
553 Py_DECREF(res);
554 }
555 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
556 res = (*f)(w, v, _Py_SwappedOp[op]);
557 if (res != Py_NotImplemented)
558 return res;
559 Py_DECREF(res);
560 }
561 /* If neither object implements it, provide a sensible default
562 for == and !=, but raise an exception for ordering. */
563 switch (op) {
564 case Py_EQ:
565 res = (v == w) ? Py_True : Py_False;
566 break;
567 case Py_NE:
568 res = (v != w) ? Py_True : Py_False;
569 break;
570 default:
571 /* XXX Special-case None so it doesn't show as NoneType() */
572 PyErr_Format(PyExc_TypeError,
573 "unorderable types: %.100s() %s %.100s()",
574 v->ob_type->tp_name,
575 opstrings[op],
576 w->ob_type->tp_name);
577 return NULL;
578 }
579 Py_INCREF(res);
580 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000581}
582
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000583/* Perform a rich comparison with object result. This wraps do_richcompare()
584 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000585
Guido van Rossume797ec12001-01-17 15:24:28 +0000586PyObject *
587PyObject_RichCompare(PyObject *v, PyObject *w, int op)
588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 assert(Py_LT <= op && op <= Py_GE);
592 if (v == NULL || w == NULL) {
593 if (!PyErr_Occurred())
594 PyErr_BadInternalCall();
595 return NULL;
596 }
597 if (Py_EnterRecursiveCall(" in comparison"))
598 return NULL;
599 res = do_richcompare(v, w, op);
600 Py_LeaveRecursiveCall();
601 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000602}
603
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000604/* Perform a rich comparison with integer result. This wraps
605 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000606int
607PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyObject *res;
610 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Quick result when objects are the same.
613 Guarantees that identity implies equality. */
614 if (v == w) {
615 if (op == Py_EQ)
616 return 1;
617 else if (op == Py_NE)
618 return 0;
619 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 res = PyObject_RichCompare(v, w, op);
622 if (res == NULL)
623 return -1;
624 if (PyBool_Check(res))
625 ok = (res == Py_True);
626 else
627 ok = PyObject_IsTrue(res);
628 Py_DECREF(res);
629 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000630}
Fred Drake13634cf2000-06-29 19:17:04 +0000631
632/* Set of hash utility functions to help maintaining the invariant that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000634
635 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
636*/
637
Mark Dickinsondc787d22010-05-23 13:33:13 +0000638/* For numeric types, the hash of a number x is based on the reduction
639 of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that
640 hash(x) == hash(y) whenever x and y are numerically equal, even if
641 x and y have different types.
642
643 A quick summary of the hashing strategy:
644
645 (1) First define the 'reduction of x modulo P' for any rational
646 number x; this is a standard extension of the usual notion of
647 reduction modulo P for integers. If x == p/q (written in lowest
648 terms), the reduction is interpreted as the reduction of p times
649 the inverse of the reduction of q, all modulo P; if q is exactly
650 divisible by P then define the reduction to be infinity. So we've
651 got a well-defined map
652
653 reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
654
655 (2) Now for a rational number x, define hash(x) by:
656
657 reduce(x) if x >= 0
658 -reduce(-x) if x < 0
659
660 If the result of the reduction is infinity (this is impossible for
661 integers, floats and Decimals) then use the predefined hash value
662 _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
663 _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the
664 hashes of float and Decimal infinities and nans.
665
666 A selling point for the above strategy is that it makes it possible
667 to compute hashes of decimal and binary floating-point numbers
668 efficiently, even if the exponent of the binary or decimal number
669 is large. The key point is that
670
671 reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
672
673 provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a
674 binary or decimal float is never infinity, since the denominator is a power
675 of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have,
676 for nonnegative x,
677
678 reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
679
680 reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
681
682 and reduce(10**e) can be computed efficiently by the usual modular
683 exponentiation algorithm. For reduce(2**e) it's even better: since
684 P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
685 by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
686
687 */
688
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000689Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000690_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000691{
Mark Dickinsondc787d22010-05-23 13:33:13 +0000692 int e, sign;
693 double m;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000694 Py_uhash_t x, y;
Tim Peters39dce292000-08-15 03:34:48 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 if (!Py_IS_FINITE(v)) {
697 if (Py_IS_INFINITY(v))
Mark Dickinsondc787d22010-05-23 13:33:13 +0000698 return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 else
Mark Dickinsondc787d22010-05-23 13:33:13 +0000700 return _PyHASH_NAN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000702
703 m = frexp(v, &e);
704
705 sign = 1;
706 if (m < 0) {
707 sign = -1;
708 m = -m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000710
711 /* process 28 bits at a time; this should work well both for binary
712 and hexadecimal floating point. */
713 x = 0;
714 while (m) {
715 x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
716 m *= 268435456.0; /* 2**28 */
717 e -= 28;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000718 y = (Py_uhash_t)m; /* pull out integer part */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000719 m -= y;
720 x += y;
721 if (x >= _PyHASH_MODULUS)
722 x -= _PyHASH_MODULUS;
723 }
724
725 /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */
726 e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
727 x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
728
729 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000730 if (x == (Py_uhash_t)-1)
731 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000732 return (Py_hash_t)x;
Fred Drake13634cf2000-06-29 19:17:04 +0000733}
734
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000735Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000736_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000737{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000738 Py_hash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 size_t y = (size_t)p;
740 /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
741 excessive hash collisions for dicts and sets */
742 y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000743 x = (Py_hash_t)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (x == -1)
745 x = -2;
746 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000747}
748
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000749Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000750PyObject_HashNotImplemented(PyObject *v)
751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
753 Py_TYPE(v)->tp_name);
754 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000755}
Fred Drake13634cf2000-06-29 19:17:04 +0000756
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100757_Py_HashSecret_t _Py_HashSecret;
758
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000759Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000760PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyTypeObject *tp = Py_TYPE(v);
763 if (tp->tp_hash != NULL)
764 return (*tp->tp_hash)(v);
765 /* To keep to the general practice that inheriting
766 * solely from object in C code should work without
767 * an explicit call to PyType_Ready, we implicitly call
768 * PyType_Ready here and then check the tp_hash slot again
769 */
770 if (tp->tp_dict == NULL) {
771 if (PyType_Ready(tp) < 0)
772 return -1;
773 if (tp->tp_hash != NULL)
774 return (*tp->tp_hash)(v);
775 }
776 /* Otherwise, the object can't be hashed */
777 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000778}
779
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000780PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000781PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (Py_TYPE(v)->tp_getattr != NULL)
786 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
787 w = PyUnicode_InternFromString(name);
788 if (w == NULL)
789 return NULL;
790 res = PyObject_GetAttr(v, w);
791 Py_XDECREF(w);
792 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000793}
794
795int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000796PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 PyObject *res = PyObject_GetAttrString(v, name);
799 if (res != NULL) {
800 Py_DECREF(res);
801 return 1;
802 }
803 PyErr_Clear();
804 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000805}
806
807int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000808PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PyObject *s;
811 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (Py_TYPE(v)->tp_setattr != NULL)
814 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
815 s = PyUnicode_InternFromString(name);
816 if (s == NULL)
817 return -1;
818 res = PyObject_SetAttr(v, s, w);
819 Py_XDECREF(s);
820 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000821}
822
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000823PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000824PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (!PyUnicode_Check(name)) {
829 PyErr_Format(PyExc_TypeError,
830 "attribute name must be string, not '%.200s'",
831 name->ob_type->tp_name);
832 return NULL;
833 }
834 if (tp->tp_getattro != NULL)
835 return (*tp->tp_getattro)(v, name);
836 if (tp->tp_getattr != NULL) {
837 char *name_str = _PyUnicode_AsString(name);
838 if (name_str == NULL)
839 return NULL;
840 return (*tp->tp_getattr)(v, name_str);
841 }
842 PyErr_Format(PyExc_AttributeError,
843 "'%.50s' object has no attribute '%U'",
844 tp->tp_name, name);
845 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000846}
847
848int
Fred Drake100814d2000-07-09 15:48:49 +0000849PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyObject *res = PyObject_GetAttr(v, name);
852 if (res != NULL) {
853 Py_DECREF(res);
854 return 1;
855 }
856 PyErr_Clear();
857 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000858}
859
860int
Fred Drake100814d2000-07-09 15:48:49 +0000861PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 PyTypeObject *tp = Py_TYPE(v);
864 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (!PyUnicode_Check(name)) {
867 PyErr_Format(PyExc_TypeError,
868 "attribute name must be string, not '%.200s'",
869 name->ob_type->tp_name);
870 return -1;
871 }
872 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyUnicode_InternInPlace(&name);
875 if (tp->tp_setattro != NULL) {
876 err = (*tp->tp_setattro)(v, name, value);
877 Py_DECREF(name);
878 return err;
879 }
880 if (tp->tp_setattr != NULL) {
881 char *name_str = _PyUnicode_AsString(name);
882 if (name_str == NULL)
883 return -1;
884 err = (*tp->tp_setattr)(v, name_str, value);
885 Py_DECREF(name);
886 return err;
887 }
888 Py_DECREF(name);
889 assert(name->ob_refcnt >= 1);
890 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
891 PyErr_Format(PyExc_TypeError,
892 "'%.100s' object has no attributes "
893 "(%s .%U)",
894 tp->tp_name,
895 value==NULL ? "del" : "assign to",
896 name);
897 else
898 PyErr_Format(PyExc_TypeError,
899 "'%.100s' object has only read-only attributes "
900 "(%s .%U)",
901 tp->tp_name,
902 value==NULL ? "del" : "assign to",
903 name);
904 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000905}
906
907/* Helper to get a pointer to an object's __dict__ slot, if any */
908
909PyObject **
910_PyObject_GetDictPtr(PyObject *obj)
911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 Py_ssize_t dictoffset;
913 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 dictoffset = tp->tp_dictoffset;
916 if (dictoffset == 0)
917 return NULL;
918 if (dictoffset < 0) {
919 Py_ssize_t tsize;
920 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 tsize = ((PyVarObject *)obj)->ob_size;
923 if (tsize < 0)
924 tsize = -tsize;
925 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 dictoffset += (long)size;
928 assert(dictoffset > 0);
929 assert(dictoffset % SIZEOF_VOID_P == 0);
930 }
931 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932}
933
Tim Peters6d6c1a32001-08-02 04:15:00 +0000934PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +0000935PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +0000936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 Py_INCREF(obj);
938 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +0000939}
940
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +0000941/* Helper used when the __next__ method is removed from a type:
942 tp_iternext is never NULL and can be safely called without checking
943 on every iteration.
944 */
945
946PyObject *
947_PyObject_NextNotImplemented(PyObject *self)
948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyErr_Format(PyExc_TypeError,
950 "'%.200s' object is not iterable",
951 Py_TYPE(self)->tp_name);
952 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +0000953}
954
Michael W. Hudson1593f502004-09-14 17:09:47 +0000955/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
956
Raymond Hettinger01538262003-03-17 08:24:35 +0000957PyObject *
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000958_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 PyTypeObject *tp = Py_TYPE(obj);
961 PyObject *descr = NULL;
962 PyObject *res = NULL;
963 descrgetfunc f;
964 Py_ssize_t dictoffset;
965 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 if (!PyUnicode_Check(name)){
968 PyErr_Format(PyExc_TypeError,
969 "attribute name must be string, not '%.200s'",
970 name->ob_type->tp_name);
971 return NULL;
972 }
973 else
974 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (tp->tp_dict == NULL) {
977 if (PyType_Ready(tp) < 0)
978 goto done;
979 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 descr = _PyType_Lookup(tp, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 f = NULL;
985 if (descr != NULL) {
986 f = descr->ob_type->tp_descr_get;
987 if (f != NULL && PyDescr_IsData(descr)) {
988 res = f(descr, obj, (PyObject *)obj->ob_type);
989 Py_DECREF(descr);
990 goto done;
991 }
992 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000993
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000994 if (dict == NULL) {
995 /* Inline _PyObject_GetDictPtr */
996 dictoffset = tp->tp_dictoffset;
997 if (dictoffset != 0) {
998 if (dictoffset < 0) {
999 Py_ssize_t tsize;
1000 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +00001001
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001002 tsize = ((PyVarObject *)obj)->ob_size;
1003 if (tsize < 0)
1004 tsize = -tsize;
1005 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001006
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001007 dictoffset += (long)size;
1008 assert(dictoffset > 0);
1009 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001011 dictptr = (PyObject **) ((char *)obj + dictoffset);
1012 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 }
1014 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001015 if (dict != NULL) {
1016 Py_INCREF(dict);
1017 res = PyDict_GetItem(dict, name);
1018 if (res != NULL) {
1019 Py_INCREF(res);
1020 Py_XDECREF(descr);
1021 Py_DECREF(dict);
1022 goto done;
1023 }
1024 Py_DECREF(dict);
1025 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (f != NULL) {
1028 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1029 Py_DECREF(descr);
1030 goto done;
1031 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (descr != NULL) {
1034 res = descr;
1035 /* descr was already increfed above */
1036 goto done;
1037 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 PyErr_Format(PyExc_AttributeError,
1040 "'%.50s' object has no attribute '%U'",
1041 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001042 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 Py_DECREF(name);
1044 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045}
1046
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001047PyObject *
1048PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1049{
1050 return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1051}
1052
Tim Peters6d6c1a32001-08-02 04:15:00 +00001053int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001054_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1055 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 PyTypeObject *tp = Py_TYPE(obj);
1058 PyObject *descr;
1059 descrsetfunc f;
1060 PyObject **dictptr;
1061 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 if (!PyUnicode_Check(name)){
1064 PyErr_Format(PyExc_TypeError,
1065 "attribute name must be string, not '%.200s'",
1066 name->ob_type->tp_name);
1067 return -1;
1068 }
1069 else
1070 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (tp->tp_dict == NULL) {
1073 if (PyType_Ready(tp) < 0)
1074 goto done;
1075 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 descr = _PyType_Lookup(tp, name);
1078 f = NULL;
1079 if (descr != NULL) {
1080 f = descr->ob_type->tp_descr_set;
1081 if (f != NULL && PyDescr_IsData(descr)) {
1082 res = f(descr, obj, value);
1083 goto done;
1084 }
1085 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001086
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001087 if (dict == NULL) {
1088 dictptr = _PyObject_GetDictPtr(obj);
1089 if (dictptr != NULL) {
1090 dict = *dictptr;
1091 if (dict == NULL && value != NULL) {
1092 dict = PyDict_New();
1093 if (dict == NULL)
1094 goto done;
1095 *dictptr = dict;
1096 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001098 }
1099 if (dict != NULL) {
1100 Py_INCREF(dict);
1101 if (value == NULL)
1102 res = PyDict_DelItem(dict, name);
1103 else
1104 res = PyDict_SetItem(dict, name, value);
1105 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1106 PyErr_SetObject(PyExc_AttributeError, name);
1107 Py_DECREF(dict);
1108 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (f != NULL) {
1112 res = f(descr, obj, value);
1113 goto done;
1114 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (descr == NULL) {
1117 PyErr_Format(PyExc_AttributeError,
1118 "'%.100s' object has no attribute '%U'",
1119 tp->tp_name, name);
1120 goto done;
1121 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 PyErr_Format(PyExc_AttributeError,
1124 "'%.50s' object attribute '%U' is read-only",
1125 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001126 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 Py_DECREF(name);
1128 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001129}
1130
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001131int
1132PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1133{
1134 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1135}
1136
1137
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001138/* Test a value used as condition, e.g., in a for or if statement.
1139 Return -1 if an error occurred */
1140
1141int
Fred Drake100814d2000-07-09 15:48:49 +00001142PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 Py_ssize_t res;
1145 if (v == Py_True)
1146 return 1;
1147 if (v == Py_False)
1148 return 0;
1149 if (v == Py_None)
1150 return 0;
1151 else if (v->ob_type->tp_as_number != NULL &&
1152 v->ob_type->tp_as_number->nb_bool != NULL)
1153 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1154 else if (v->ob_type->tp_as_mapping != NULL &&
1155 v->ob_type->tp_as_mapping->mp_length != NULL)
1156 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1157 else if (v->ob_type->tp_as_sequence != NULL &&
1158 v->ob_type->tp_as_sequence->sq_length != NULL)
1159 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1160 else
1161 return 1;
1162 /* if it is negative, it should be either -1 or -2 */
1163 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001164}
1165
Tim Peters803526b2002-07-07 05:13:56 +00001166/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001167 Return -1 if an error occurred */
1168
1169int
Fred Drake100814d2000-07-09 15:48:49 +00001170PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 int res;
1173 res = PyObject_IsTrue(v);
1174 if (res < 0)
1175 return res;
1176 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001177}
1178
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001179/* Test whether an object can be called */
1180
1181int
Fred Drake100814d2000-07-09 15:48:49 +00001182PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (x == NULL)
1185 return 0;
1186 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001187}
1188
Georg Brandle32b4222007-03-10 22:13:27 +00001189/* ------------------------- PyObject_Dir() helpers ------------------------- */
1190
Tim Peters7eea37e2001-09-04 22:08:56 +00001191/* Helper for PyObject_Dir.
1192 Merge the __dict__ of aclass into dict, and recursively also all
1193 the __dict__s of aclass's base classes. The order of merging isn't
1194 defined, as it's expected that only the final set of dict keys is
1195 interesting.
1196 Return 0 on success, -1 on error.
1197*/
1198
1199static int
1200merge_class_dict(PyObject* dict, PyObject* aclass)
1201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyObject *classdict;
1203 PyObject *bases;
Tim Peters7eea37e2001-09-04 22:08:56 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 assert(PyDict_Check(dict));
1206 assert(aclass);
Tim Peters7eea37e2001-09-04 22:08:56 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* Merge in the type's dict (if any). */
1209 classdict = PyObject_GetAttrString(aclass, "__dict__");
1210 if (classdict == NULL)
1211 PyErr_Clear();
1212 else {
1213 int status = PyDict_Update(dict, classdict);
1214 Py_DECREF(classdict);
1215 if (status < 0)
1216 return -1;
1217 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 /* Recursively merge in the base types' (if any) dicts. */
1220 bases = PyObject_GetAttrString(aclass, "__bases__");
1221 if (bases == NULL)
1222 PyErr_Clear();
1223 else {
1224 /* We have no guarantee that bases is a real tuple */
1225 Py_ssize_t i, n;
1226 n = PySequence_Size(bases); /* This better be right */
1227 if (n < 0)
1228 PyErr_Clear();
1229 else {
1230 for (i = 0; i < n; i++) {
1231 int status;
1232 PyObject *base = PySequence_GetItem(bases, i);
1233 if (base == NULL) {
1234 Py_DECREF(bases);
1235 return -1;
1236 }
1237 status = merge_class_dict(dict, base);
1238 Py_DECREF(base);
1239 if (status < 0) {
1240 Py_DECREF(bases);
1241 return -1;
1242 }
1243 }
1244 }
1245 Py_DECREF(bases);
1246 }
1247 return 0;
Tim Peters7eea37e2001-09-04 22:08:56 +00001248}
1249
Georg Brandle32b4222007-03-10 22:13:27 +00001250/* Helper for PyObject_Dir without arguments: returns the local scope. */
1251static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001252_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 PyObject *names;
1255 PyObject *locals = PyEval_GetLocals();
Tim Peters305b5852001-09-17 02:38:46 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (locals == NULL) {
1258 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1259 return NULL;
1260 }
Tim Peters305b5852001-09-17 02:38:46 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 names = PyMapping_Keys(locals);
1263 if (!names)
1264 return NULL;
1265 if (!PyList_Check(names)) {
1266 PyErr_Format(PyExc_TypeError,
1267 "dir(): expected keys() of locals to be a list, "
1268 "not '%.200s'", Py_TYPE(names)->tp_name);
1269 Py_DECREF(names);
1270 return NULL;
1271 }
1272 /* the locals don't need to be DECREF'd */
1273 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001274}
1275
1276/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
Guido van Rossum98297ee2007-11-06 21:34:58 +00001277 We deliberately don't suck up its __class__, as methods belonging to the
1278 metaclass would probably be more confusing than helpful.
Georg Brandle32b4222007-03-10 22:13:27 +00001279*/
Guido van Rossum98297ee2007-11-06 21:34:58 +00001280static PyObject *
Georg Brandle32b4222007-03-10 22:13:27 +00001281_specialized_dir_type(PyObject *obj)
1282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 PyObject *result = NULL;
1284 PyObject *dict = PyDict_New();
Georg Brandle32b4222007-03-10 22:13:27 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1287 result = PyDict_Keys(dict);
Georg Brandle32b4222007-03-10 22:13:27 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 Py_XDECREF(dict);
1290 return result;
Tim Peters305b5852001-09-17 02:38:46 +00001291}
1292
Georg Brandle32b4222007-03-10 22:13:27 +00001293/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1294static PyObject *
1295_specialized_dir_module(PyObject *obj)
Tim Peters7eea37e2001-09-04 22:08:56 +00001296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 PyObject *result = NULL;
1298 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
Tim Peters7eea37e2001-09-04 22:08:56 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (dict != NULL) {
1301 if (PyDict_Check(dict))
1302 result = PyDict_Keys(dict);
1303 else {
1304 const char *name = PyModule_GetName(obj);
1305 if (name)
1306 PyErr_Format(PyExc_TypeError,
1307 "%.200s.__dict__ is not a dictionary",
1308 name);
1309 }
1310 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 Py_XDECREF(dict);
1313 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001314}
Tim Peters7eea37e2001-09-04 22:08:56 +00001315
Georg Brandle32b4222007-03-10 22:13:27 +00001316/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1317 and recursively up the __class__.__bases__ chain.
1318*/
1319static PyObject *
1320_generic_dir(PyObject *obj)
1321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 PyObject *result = NULL;
1323 PyObject *dict = NULL;
1324 PyObject *itsclass = NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 /* Get __dict__ (which may or may not be a real dict...) */
1327 dict = PyObject_GetAttrString(obj, "__dict__");
1328 if (dict == NULL) {
1329 PyErr_Clear();
1330 dict = PyDict_New();
1331 }
1332 else if (!PyDict_Check(dict)) {
1333 Py_DECREF(dict);
1334 dict = PyDict_New();
1335 }
1336 else {
1337 /* Copy __dict__ to avoid mutating it. */
1338 PyObject *temp = PyDict_Copy(dict);
1339 Py_DECREF(dict);
1340 dict = temp;
1341 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 if (dict == NULL)
1344 goto error;
Tim Peters7eea37e2001-09-04 22:08:56 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* Merge in attrs reachable from its class. */
1347 itsclass = PyObject_GetAttrString(obj, "__class__");
1348 if (itsclass == NULL)
1349 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1350 __class__ exists? */
1351 PyErr_Clear();
1352 else {
1353 if (merge_class_dict(dict, itsclass) != 0)
1354 goto error;
1355 }
Georg Brandle32b4222007-03-10 22:13:27 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 result = PyDict_Keys(dict);
1358 /* fall through */
Georg Brandle32b4222007-03-10 22:13:27 +00001359error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 Py_XDECREF(itsclass);
1361 Py_XDECREF(dict);
1362 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001363}
1364
1365/* Helper for PyObject_Dir: object introspection.
1366 This calls one of the above specialized versions if no __dir__ method
1367 exists. */
1368static PyObject *
1369_dir_object(PyObject *obj)
1370{
Benjamin Peterson7963a352011-05-23 16:11:05 -05001371 PyObject *result = NULL;
1372 static PyObject *dir_str = NULL;
1373 PyObject *dirfunc = _PyObject_LookupSpecial(obj, "__dir__", &dir_str);
Georg Brandle32b4222007-03-10 22:13:27 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 assert(obj);
1376 if (dirfunc == NULL) {
Benjamin Peterson7963a352011-05-23 16:11:05 -05001377 if (PyErr_Occurred())
1378 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* use default implementation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (PyModule_Check(obj))
1381 result = _specialized_dir_module(obj);
1382 else if (PyType_Check(obj))
1383 result = _specialized_dir_type(obj);
1384 else
1385 result = _generic_dir(obj);
1386 }
1387 else {
1388 /* use __dir__ */
Benjamin Peterson7963a352011-05-23 16:11:05 -05001389 result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 Py_DECREF(dirfunc);
1391 if (result == NULL)
1392 return NULL;
Georg Brandle32b4222007-03-10 22:13:27 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 /* result must be a list */
1395 /* XXX(gbrandl): could also check if all items are strings */
1396 if (!PyList_Check(result)) {
1397 PyErr_Format(PyExc_TypeError,
1398 "__dir__() must return a list, not %.200s",
1399 Py_TYPE(result)->tp_name);
1400 Py_DECREF(result);
1401 result = NULL;
1402 }
1403 }
Georg Brandle32b4222007-03-10 22:13:27 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001406}
1407
1408/* Implementation of dir() -- if obj is NULL, returns the names in the current
1409 (local) scope. Otherwise, performs introspection of the object: returns a
1410 sorted list of attribute names (supposedly) accessible from the object
1411*/
1412PyObject *
1413PyObject_Dir(PyObject *obj)
1414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PyObject * result;
Georg Brandle32b4222007-03-10 22:13:27 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (obj == NULL)
1418 /* no object -- introspect the locals */
1419 result = _dir_locals();
1420 else
1421 /* object -- introspect the object */
1422 result = _dir_object(obj);
Georg Brandle32b4222007-03-10 22:13:27 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 assert(result == NULL || PyList_Check(result));
Georg Brandle32b4222007-03-10 22:13:27 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (result != NULL && PyList_Sort(result) != 0) {
1427 /* sorting the list failed */
1428 Py_DECREF(result);
1429 result = NULL;
1430 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 return result;
Tim Peters7eea37e2001-09-04 22:08:56 +00001433}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001434
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001435/*
1436NoObject is usable as a non-NULL undefined value, used by the macro None.
1437There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001438so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001439(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001440*/
1441
Guido van Rossum0c182a11992-03-27 17:26:13 +00001442/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001443static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001444none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001447}
1448
Barry Warsaw9bf16442001-01-23 16:24:35 +00001449/* ARGUSED */
1450static void
Tim Peters803526b2002-07-07 05:13:56 +00001451none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 /* This should never get called, but we also don't want to SEGV if
1454 * we accidentally decref None out of existence.
1455 */
1456 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001457}
1458
1459
Guido van Rossumba21a492001-08-16 08:17:26 +00001460static PyTypeObject PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1462 "NoneType",
1463 0,
1464 0,
1465 none_dealloc, /*tp_dealloc*/ /*never called*/
1466 0, /*tp_print*/
1467 0, /*tp_getattr*/
1468 0, /*tp_setattr*/
1469 0, /*tp_reserved*/
1470 none_repr, /*tp_repr*/
1471 0, /*tp_as_number*/
1472 0, /*tp_as_sequence*/
1473 0, /*tp_as_mapping*/
1474 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001475};
1476
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001477PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001478 _PyObject_EXTRA_INIT
1479 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001480};
1481
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001482/* NotImplemented is an object that can be used to signal that an
1483 operation is not implemented for the given type combination. */
1484
1485static PyObject *
1486NotImplemented_repr(PyObject *op)
1487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001489}
1490
1491static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1493 "NotImplementedType",
1494 0,
1495 0,
1496 none_dealloc, /*tp_dealloc*/ /*never called*/
1497 0, /*tp_print*/
1498 0, /*tp_getattr*/
1499 0, /*tp_setattr*/
1500 0, /*tp_reserved*/
1501 NotImplemented_repr, /*tp_repr*/
1502 0, /*tp_as_number*/
1503 0, /*tp_as_sequence*/
1504 0, /*tp_as_mapping*/
1505 0, /*tp_hash */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001506};
1507
1508PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 _PyObject_EXTRA_INIT
1510 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001511};
1512
Guido van Rossumba21a492001-08-16 08:17:26 +00001513void
1514_Py_ReadyTypes(void)
1515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 if (PyType_Ready(&PyType_Type) < 0)
1517 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1520 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1523 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1526 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (PyType_Ready(&PyBool_Type) < 0)
1529 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (PyType_Ready(&PyByteArray_Type) < 0)
1532 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (PyType_Ready(&PyBytes_Type) < 0)
1535 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (PyType_Ready(&PyList_Type) < 0)
1538 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 if (PyType_Ready(&PyNone_Type) < 0)
1541 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1544 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (PyType_Ready(&PyTraceBack_Type) < 0)
1547 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (PyType_Ready(&PySuper_Type) < 0)
1550 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 if (PyType_Ready(&PyBaseObject_Type) < 0)
1553 Py_FatalError("Can't initialize object type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (PyType_Ready(&PyRange_Type) < 0)
1556 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 if (PyType_Ready(&PyDict_Type) < 0)
1559 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 if (PyType_Ready(&PySet_Type) < 0)
1562 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 if (PyType_Ready(&PyUnicode_Type) < 0)
1565 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (PyType_Ready(&PySlice_Type) < 0)
1568 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1571 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (PyType_Ready(&PyComplex_Type) < 0)
1574 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (PyType_Ready(&PyFloat_Type) < 0)
1577 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 if (PyType_Ready(&PyLong_Type) < 0)
1580 Py_FatalError("Can't initialize int type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1583 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (PyType_Ready(&PyProperty_Type) < 0)
1586 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (PyType_Ready(&PyMemoryView_Type) < 0)
1589 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 if (PyType_Ready(&PyTuple_Type) < 0)
1592 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 if (PyType_Ready(&PyEnum_Type) < 0)
1595 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 if (PyType_Ready(&PyReversed_Type) < 0)
1598 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1601 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (PyType_Ready(&PyCode_Type) < 0)
1604 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (PyType_Ready(&PyFrame_Type) < 0)
1607 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (PyType_Ready(&PyCFunction_Type) < 0)
1610 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 if (PyType_Ready(&PyMethod_Type) < 0)
1613 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 if (PyType_Ready(&PyFunction_Type) < 0)
1616 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (PyType_Ready(&PyDictProxy_Type) < 0)
1619 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 if (PyType_Ready(&PyGen_Type) < 0)
1622 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1625 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1628 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001629
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001630 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1631 Py_FatalError("Can't initialize method wrapper type");
1632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 if (PyType_Ready(&PyEllipsis_Type) < 0)
1634 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1637 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (PyType_Ready(&PyFilter_Type) < 0)
1640 Py_FatalError("Can't initialize filter type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (PyType_Ready(&PyMap_Type) < 0)
1643 Py_FatalError("Can't initialize map type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 if (PyType_Ready(&PyZip_Type) < 0)
1646 Py_FatalError("Can't initialize zip type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001647}
1648
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001649
Guido van Rossum84a90321996-05-22 16:34:47 +00001650#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001651
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001652void
Fred Drake100814d2000-07-09 15:48:49 +00001653_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 _Py_INC_REFTOTAL;
1656 op->ob_refcnt = 1;
1657 _Py_AddToAllObjects(op, 1);
1658 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001659}
1660
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001661void
Fred Drake100814d2000-07-09 15:48:49 +00001662_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001663{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001664#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001666#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 if (op->ob_refcnt < 0)
1668 Py_FatalError("UNREF negative refcnt");
1669 if (op == &refchain ||
1670 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1671 fprintf(stderr, "* ob\n");
1672 _PyObject_Dump(op);
1673 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1674 _PyObject_Dump(op->_ob_prev->_ob_next);
1675 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1676 _PyObject_Dump(op->_ob_next->_ob_prev);
1677 Py_FatalError("UNREF invalid object");
1678 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001679#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1681 if (p == op)
1682 break;
1683 }
1684 if (p == &refchain) /* Not found */
1685 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001686#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 op->_ob_next->_ob_prev = op->_ob_prev;
1688 op->_ob_prev->_ob_next = op->_ob_next;
1689 op->_ob_next = op->_ob_prev = NULL;
1690 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001691}
1692
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001693void
Fred Drake100814d2000-07-09 15:48:49 +00001694_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1697 _Py_ForgetReference(op);
1698 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001699}
1700
Tim Peters269b2a62003-04-17 19:52:29 +00001701/* Print all live objects. Because PyObject_Print is called, the
1702 * interpreter must be in a healthy state.
1703 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001704void
Fred Drake100814d2000-07-09 15:48:49 +00001705_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 PyObject *op;
1708 fprintf(fp, "Remaining objects:\n");
1709 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1710 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1711 if (PyObject_Print(op, fp, 0) != 0)
1712 PyErr_Clear();
1713 putc('\n', fp);
1714 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001715}
1716
Tim Peters269b2a62003-04-17 19:52:29 +00001717/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1718 * doesn't make any calls to the Python C API, so is always safe to call.
1719 */
1720void
1721_Py_PrintReferenceAddresses(FILE *fp)
1722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyObject *op;
1724 fprintf(fp, "Remaining object addresses:\n");
1725 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1726 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1727 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001728}
1729
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001730PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001731_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 int i, n;
1734 PyObject *t = NULL;
1735 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1738 return NULL;
1739 op = refchain._ob_next;
1740 res = PyList_New(0);
1741 if (res == NULL)
1742 return NULL;
1743 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1744 while (op == self || op == args || op == res || op == t ||
1745 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1746 op = op->_ob_next;
1747 if (op == &refchain)
1748 return res;
1749 }
1750 if (PyList_Append(res, op) < 0) {
1751 Py_DECREF(res);
1752 return NULL;
1753 }
1754 op = op->_ob_next;
1755 }
1756 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001757}
1758
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001759#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001760
Benjamin Petersonb173f782009-05-05 22:31:58 +00001761/* Hack to force loading of pycapsule.o */
1762PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
1763
1764
Guido van Rossum84a90321996-05-22 16:34:47 +00001765/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001766Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001767
1768
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001769/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001770
Thomas Wouters334fb892000-07-25 12:56:38 +00001771void *
Fred Drake100814d2000-07-09 15:48:49 +00001772PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001775}
1776
Thomas Wouters334fb892000-07-25 12:56:38 +00001777void *
1778PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001781}
1782
1783void
Thomas Wouters334fb892000-07-25 12:56:38 +00001784PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyMem_FREE(p);
Guido van Rossumb18618d2000-05-03 23:44:39 +00001787}
1788
1789
Guido van Rossum86610361998-04-10 22:32:46 +00001790/* These methods are used to control infinite recursion in repr, str, print,
1791 etc. Container objects that may recursively contain themselves,
1792 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1793 Py_ReprLeave() to avoid infinite recursion.
1794
1795 Py_ReprEnter() returns 0 the first time it is called for a particular
1796 object and 1 every time thereafter. It returns -1 if an exception
1797 occurred. Py_ReprLeave() has no return value.
1798
1799 See dictobject.c and listobject.c for examples of use.
1800*/
1801
1802#define KEY "Py_Repr"
1803
1804int
Fred Drake100814d2000-07-09 15:48:49 +00001805Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 PyObject *dict;
1808 PyObject *list;
1809 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 dict = PyThreadState_GetDict();
1812 if (dict == NULL)
1813 return 0;
1814 list = PyDict_GetItemString(dict, KEY);
1815 if (list == NULL) {
1816 list = PyList_New(0);
1817 if (list == NULL)
1818 return -1;
1819 if (PyDict_SetItemString(dict, KEY, list) < 0)
1820 return -1;
1821 Py_DECREF(list);
1822 }
1823 i = PyList_GET_SIZE(list);
1824 while (--i >= 0) {
1825 if (PyList_GET_ITEM(list, i) == obj)
1826 return 1;
1827 }
1828 PyList_Append(list, obj);
1829 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001830}
1831
1832void
Fred Drake100814d2000-07-09 15:48:49 +00001833Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyObject *dict;
1836 PyObject *list;
1837 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 dict = PyThreadState_GetDict();
1840 if (dict == NULL)
1841 return;
1842 list = PyDict_GetItemString(dict, KEY);
1843 if (list == NULL || !PyList_Check(list))
1844 return;
1845 i = PyList_GET_SIZE(list);
1846 /* Count backwards because we always expect obj to be list[-1] */
1847 while (--i >= 0) {
1848 if (PyList_GET_ITEM(list, i) == obj) {
1849 PyList_SetSlice(list, i, i + 1, NULL);
1850 break;
1851 }
1852 }
Guido van Rossum86610361998-04-10 22:32:46 +00001853}
Guido van Rossumd724b232000-03-13 16:01:29 +00001854
Tim Peters803526b2002-07-07 05:13:56 +00001855/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001856
Tim Peters803526b2002-07-07 05:13:56 +00001857/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001858int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001859
Tim Peters803526b2002-07-07 05:13:56 +00001860/* List of objects that still need to be cleaned up, singly linked via their
1861 * gc headers' gc_prev pointers.
1862 */
1863PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001864
Tim Peters803526b2002-07-07 05:13:56 +00001865/* Add op to the _PyTrash_delete_later list. Called when the current
1866 * call-stack depth gets large. op must be a currently untracked gc'ed
1867 * object, with refcount 0. Py_DECREF must already have been called on it.
1868 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001869void
Fred Drake100814d2000-07-09 15:48:49 +00001870_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 assert(PyObject_IS_GC(op));
1873 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1874 assert(op->ob_refcnt == 0);
1875 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
1876 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001877}
1878
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001879/* The equivalent API, using per-thread state recursion info */
1880void
1881_PyTrash_thread_deposit_object(PyObject *op)
1882{
1883 PyThreadState *tstate = PyThreadState_GET();
1884 assert(PyObject_IS_GC(op));
1885 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1886 assert(op->ob_refcnt == 0);
1887 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *) tstate->trash_delete_later;
1888 tstate->trash_delete_later = op;
1889}
1890
Tim Peters803526b2002-07-07 05:13:56 +00001891/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1892 * the call-stack unwinds again.
1893 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001894void
Fred Drake100814d2000-07-09 15:48:49 +00001895_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 while (_PyTrash_delete_later) {
1898 PyObject *op = _PyTrash_delete_later;
1899 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 _PyTrash_delete_later =
1902 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* Call the deallocator directly. This used to try to
1905 * fool Py_DECREF into calling it indirectly, but
1906 * Py_DECREF was already called on this object, and in
1907 * assorted non-release builds calling Py_DECREF again ends
1908 * up distorting allocation statistics.
1909 */
1910 assert(op->ob_refcnt == 0);
1911 ++_PyTrash_delete_nesting;
1912 (*dealloc)(op);
1913 --_PyTrash_delete_nesting;
1914 }
Guido van Rossumd724b232000-03-13 16:01:29 +00001915}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001916
Antoine Pitrou56cd62c2012-09-06 00:59:49 +02001917/* The equivalent API, using per-thread state recursion info */
1918void
1919_PyTrash_thread_destroy_chain(void)
1920{
1921 PyThreadState *tstate = PyThreadState_GET();
1922 while (tstate->trash_delete_later) {
1923 PyObject *op = tstate->trash_delete_later;
1924 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1925
1926 tstate->trash_delete_later =
1927 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
1928
1929 /* Call the deallocator directly. This used to try to
1930 * fool Py_DECREF into calling it indirectly, but
1931 * Py_DECREF was already called on this object, and in
1932 * assorted non-release builds calling Py_DECREF again ends
1933 * up distorting allocation statistics.
1934 */
1935 assert(op->ob_refcnt == 0);
1936 ++tstate->trash_delete_nesting;
1937 (*dealloc)(op);
1938 --tstate->trash_delete_nesting;
1939 }
1940}
1941
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001942#ifndef Py_TRACE_REFS
1943/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
1944 Define this here, so we can undefine the macro. */
1945#undef _Py_Dealloc
1946PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
1947void
1948_Py_Dealloc(PyObject *op)
1949{
1950 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
1951 (*Py_TYPE(op)->tp_dealloc)(op);
1952}
1953#endif
1954
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001955#ifdef __cplusplus
1956}
1957#endif